cumsum till condition is met

1 回表示 (過去 30 日間)
Housam
Housam 2021 年 2 月 1 日
回答済み: Housam 2021 年 2 月 7 日
I want to compare two matrices, each with a size of [35039 1], when the number in the first matrix M1 is bigger than the number in the second matrix M2, then I want the result as the bigger number. However, when the number in M1 is smaller than the number in M2, then I want the result to be the sum of the previous numbers in M1 till the condition is met. i imagine the code to be like this:
M1=[270;270;270;270;270;270;270;270;270;270;270;270;270;270;270;270;270;270;270;270;270]
M2=[100;100;100;500;500;500;100;100;100;100;100;100;100;600;600;600;600;600;600;100;100]
compare=M1>M2 % the condition
[row11,~,~]=find( compare )
M3(row11)= M1(row11)
[row22,~,~]=find( ~compare )
M3(row22)= 0
between = cumsum(M1(1:3),1,'reverse') %sum previous "non zero" elements in M1 starting from last number
M3(row22(1)) = between(1) % replace the first element that doesnt meet the condition M2(row22(1))
% with between(1) which is the new aggregated number, that is greater than M2(4)
%similarly, i want to repeat these steps to get M3.
between2 = cumsum ( M3(1:4),2,'reverse' )
M3(row22(2)) = between2(2)
between3 = cumsum ( M3(1:5),2,'reverse' )
M3(row22(3)) = between3(5)
between4 = cumsum ( M3(1:13),2,'reverse' )
M3(row22(4)) = between4(11)
  4 件のコメント
Jan
Jan 2021 年 2 月 5 日
The description is not clear yet. What is the wanted output for:
M1 = [1, 1]; M2 = [2, 2];
What does "sum of the previous numbers in M1 till the condition is met" mean in this case?
Housam
Housam 2021 年 2 月 5 日
編集済み: Housam 2021 年 2 月 5 日
you are right @Jan, when the initial numbers are as in the case you suggested, then the calculation will not work. My initial numbers however are similar to the example above. The comparison starts with bigger numbers in M1.
I tried in the example to formulate the problem in a clear way as much as possible. Thank you in advance for a reply.

サインインしてコメントする。

採用された回答

Housam
Housam 2021 年 2 月 7 日
got it solved. Thanks all

その他の回答 (1 件)

darova
darova 2021 年 2 月 1 日
編集済み: darova 2021 年 2 月 1 日
Here is a example
s = 0;
for i = 1:length(M1)
s = s + M1(i);
if M1(i) > M2(i)
s = 0;
M3(i) = M1(i);
else
M3(i) = s;
end
end

カテゴリ

Help Center および File ExchangeGraphics Object Programming についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by