Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 根据重复索引对数组求和_Arrays_Matlab - Fatal编程技术网

Arrays 根据重复索引对数组求和

Arrays 根据重复索引对数组求和,arrays,matlab,Arrays,Matlab,我有一个两行数组a,如下所示。当第一行中的索引重复时,我想对第二行中的元素求和,并最终生成一个矩阵B。 如何在MATLAB中实现它 A = [1, 2, 2, 1, 2, 1, 2, 2, 1; 1, 2, 3, 4, 5, 1, 2, 3, 4]; B = [1, 2, 1, 2, 1, 2, 1; 1, 5, 4, 5, 1, 5, 4]; 我尝试使用diff函数(见下文)计算索引 d = diff(A(1,:))==0 goodIdx = ~([d',false]|

我有一个两行数组
a
,如下所示。当第一行中的索引重复时,我想对第二行中的元素求和,并最终生成一个矩阵
B
。 如何在MATLAB中实现它

A = [1, 2, 2, 1, 2, 1, 2, 2, 1;
     1, 2, 3, 4, 5, 1, 2, 3, 4];

B = [1, 2, 1, 2, 1, 2, 1;
     1, 5, 4, 5, 1, 5, 4];
我尝试使用
diff
函数(见下文)计算索引

d = diff(A(1,:))==0
goodIdx = ~([d',false]|[false,d'])
但我不知道如何继续下去


谢谢。

这是一种可能的方法:

A = [1, 2, 2, 1, 2, 1, 2, 2, 1;
     1, 2, 3, 4, 5, 1, 2, 3, 4];           % data
ind = [true diff(A(1,:))~=0];              % logical indices of "new" values
s = accumarray(cumsum(ind).', A(2,:).').'; % sum values in second row of A in groups 
                                           % defined by the cumulative sum of ind
B = [A(1,ind); s];                         % build result