所以,我有一个包含2列和5行的矩阵(作为例子)。
2 1
5 1
3 1
4 1
7 1
我想做的是:
从位置(1,1)开始并向下移动第一列,找到导致值<10的单元格。在这种情况下,我会:
step 1: 2 = 10? No, continue
step 2: 2+5 = 10? No, continue
step 3: 2+5+3 = 10? Yes, stop and return the sum of the corresponding values in the second column
step 4: 4 = 10? No, continue
step 5: 4+7 = 10? No, it's larger, thus we save the previous step and return 1 form the second column.
在这个过程的最后,我需要获得一个如下所示的新矩阵:
10 3
4 1
7 1
答案 0 :(得分:1)
您可以完全执行循环中描述的逻辑。
每一行,测试&#34;最近的总和&#34;,其中&#34;最近&#34;这意味着从最后一个输出行到当前行。
如果总和为10或更多,请按所述添加到输出。否则继续下一行。
代码:
% Original data
x =[2 1; 5 1; 3 1; 4 1; 7 1];
% Output for result
output = [];
% idx is the row we start sum from on each test
idx = 1;
% Loop over all rows
for ii = 1:size(x,1)
% Get sum in column 1
s = sum(x(idx:ii, 1));
if s == 10
% Append row with sums
output = [output; 10 sum(x(idx:ii,2))];
idx = ii+1;
elseif s > 10
% Append all "recent" rows
output = [output; x(idx:ii,:)];
idx = ii+1;
end
end
结果:
>> disp(output)
10 3
4 1
7 1
答案 1 :(得分:0)
这是我提议的解决方案:
SomeFramework.framework
通过获取位于指定阈值(在这种情况下为% Create A and the cumulative sum of its first column...
A = [2 1; 5 1; 3 1; 4 1; 7 1];
A_cs = cumsum(A(:,1));
% Create a variable R to store the result and an indexer to it...
R = NaN(size(A_cs,1),2);
R_off = 1;
% Perform the computation...
while (~isempty(A_cs))
idx = find(A_cs <= 10);
idx_max = max(idx);
R(R_off,:) = [A_cs(idx_max) sum(A(idx,2))];
A_cs = A_cs - A_cs(idx_max);
disp(A_cs);
A_cs(idx) = [];
R_off = R_off + 1;
end
% Clear unused slots in R...
R(any(isnan(R),2),:) = [];
)内的第一个cumsum组的最大索引来执行计算。找到后,将其相应的值插入到结果矩阵中,并通过删除组条目并减去它们的总和来更新cumsum数组。当cumsum数组为空时,迭代结束,10
包含所需的结果。