srinsp的个人博客分享 http://blog.sciencenet.cn/u/srinsp

博文

玩转向量化函数1:向量化函数accumarray

已有 4042 次阅读 2014-1-3 11:11 |系统分类:科研笔记

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 = 12 424】,则可知向量A的最大下标是4,但是没下标3,这时A3=0Elements of A that are not referred to byany row of SUBS contain zero)。接下来是如何对val进行计算了:向量val的每一元素和subs中相应的行一一对应。例如subs(1) = 1val1 = 101subs(1)val1)是一一对应的,然后就是计算A了,Asubs1)) = sum(所有与subsi=subs1)相对应的向量val中的元素之和)subs=[1;2;4;2;4];向量中的最大下标值是4,故

A中元素有A(1),A(2),A(3),A(4);
因为subs中没有3,所以A(3) =0;
只有subs1 = 1,故A1)等于与subs1)对应的元素val1
A
1 = val1=101
subs
2 = subs4 = 2,故A2 = val2+val4=206
subs
3 = subs5 = 4,故A4 = val3+val5 =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:

val = 101:105;
subs = [1 1 1; 2 1 2; 2 3 2; 2 1 2; 2 3 2];

A = accumarray(subs, val)
A(:,:,1) =
1010 0
0  0 0
A(:,:,2) =
0  0  0
2060 208

这个和前面的那个例子差不多
subs
里面最大的是(2,3,2),所以A2*3*2的矩阵
subs
里面的(1,1,1)只有一个,val的第1个位置,所以A(1,1,1)=val(1);
subs
里面的(2,1,2)2,val的第2个位置和第4个位置,所以A(2,1,2)=val(2)+val(4);
subs
里面的(2,3,2)2,val的第3个位置和第5个位置,所以A(2,3,2)=val(3)+val(5);

 



https://blog.sciencenet.cn/blog-1065241-755439.html

上一篇:随机共振讨论之十一:白噪声
下一篇:多谢各位博士关注,我来的有点少以后多更新内容
收藏 IP: 218.201.115.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-12-22 14:22

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部