|
1:向量化函数accumarray
Syntax
A = accumarray(subs,val)
A = accumarray(subs,val,sz)
A = accumarray(subs,val,sz,fun)
A = accumarray(subs,val,sz,fun,fillval)
A =accumarray(subs,val,sz,fun,fillval,issparse)
A = accumarray({subs1, subs2, ...}, val,...)
Description
accumarray groups elements from a data setand applies a function to each group. A = accumarray(subs,val) creates an arrayA by accumulating elements of the vector val using the elements of subs asindices. The position of an element in subs determines which value of vals itselects for the accumulated vector; the value of an element in subs determinesthe position of the accumulated vector in the output.
例子1
Create a 5-by-1vector and sum values for repeated 1-D subscripts:
val = 101:105;
subs = [1; 2; 4; 2; 4]
subs =
1---- val(1) = [101]
2 ---- val(2) = [102]
4 ---- val(3) = [103]
2 ---- val(4) = [104]
4 ---- val(5) = [105]
A = accumarray(subs, val)
A =
101 % A(1) = val(1) = 101
206 % A(2) = val(2)+val(4) = 102+104 = 206
0 % A(3) = 0
208 % A(4) = val(3)+val(5) = 103+105 = 208
subs定义了向量A的下标向量,例如subs = 【1;2 ;4;2;4】,则可知向量A的最大下标是4,但是没下标3,这时A(3)=0(Elements of A that are not referred to byany row of SUBS contain zero)。接下来是如何对val进行计算了:向量val的每一元素和subs中相应的行一一对应。例如subs(1) = 1;val(1) = 101,subs(1)和val(1)是一一对应的,然后就是计算A了,A(subs(1)) = sum(所有与subs(i)=subs(1)相对应的向量val中的元素之和)subs=[1;2;4;2;4];向量中的最大下标值是4,故
A中元素有A(1),A(2),A(3),A(4);
因为subs中没有3,所以A(3) =0;
只有subs(1) = 1,故A(1)等于与subs(1)对应的元素val(1)
A(1) = val(1)=101;
subs(2) = subs(4) = 2,故A(2) = val(2)+val(4)=206,
subs(3) = subs(5) = 4,故A(4) = val(3)+val(5) =208.
例子2:
val = [1, 2, 3, 4];
subs=[ 1,2; 1,1; 2,1; 1,1];
A=accumarray(subs,val)
A =
6 1
3 0
这个例子中,subs的4个行向量表明了val的4个分量分别累计入结果矩阵的(1,2)、(1,1)、(2,1)、(1,1)元素。
subs=[ 1,2; ---- val(1) = [1]
1,1; ---- val(2) = [3]
2,1; ---- val(3) = [3]
1,1];---- val(4) = [4]
例子3
Create a 2-by-3-by-2 arrayand sum values for repeated 3-D subscripts:
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-12-22 14:22
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社