我有一个带有percantage值的矩阵,其中每一行代表一个单独的观察。我需要计算累积乘积,其中这些值对应于相同的下标。我尝试使用accumarray
函数,只要我使用列向量作为值(而不是矩阵),它就可以正常工作。
我想知道在没有循环遍历值矩阵的各个列的情况下解决问题的最佳方法是什么?
这是我的示例代码:
subs = [1;1;1;2;2;2;2;2;3;3;4;4;4];
vals1 = [0.1;0.05;0.2;0.02;0.09;0.3;0.01;0.21;0.12;0.06;0.08;0.12;0.05];
% This is working as expected
result1 = accumarray(subs,vals1, [], @(x) prod(1+x) -1)
vals2 = [vals1,vals1];
% This is not working as the second input parameter of accumarray
% apperently must be a vector (rather than a matrix)
result2 = accumarray(subs, vals2, [], @(x) prod(1+x) -1)
答案 0 :(得分:0)
对于val,您可以将其设置为1:size(vals2,1)
并使用它来提取vals2
行。此函数还需要返回单元格。
result2 = accumarray(subs, 1:size(vals2,1), [], @(x) {prod(1+vals2(x,:),1)-1})
您可以连接单元格元素:
result3 = vertcat(result2{:})
或全部在一行:
result3 = cell2mat( accumarray(subs, 1:size(vals2,1), [], @(x) {prod(1+vals2(x,:),1)-1}))
result3 =
0.38600 0.38600
0.76635 0.76635
0.18720 0.18720
0.27008 0.27008
使用[10000 x 200]
矩阵作为输入比较三种提议方法的Octave测试结果:
subs = randi(1000,10000,1);
vals2 = rand(10000,200);
=========CELL2MAT========
Elapsed time is 0.130961 seconds.
=========NDGRID========
Elapsed time is 3.96383 seconds.
=========FOR LOOP========
Elapsed time is 6.16265 seconds.
答案 1 :(得分:0)