フィルターのクリア

Sum row 2 and stop when 1 is reached in row 1

1 回表示 (過去 30 日間)
Iris Willaert
Iris Willaert 2022 年 2 月 14 日
コメント済み: Image Analyst 2022 年 2 月 17 日
Hi,
I have a array of two rows with the following numbers:
Row1: [0,0,1,0,0,0,1,0,0,1,0]
Row2: [0.0220,0.3110,0.0230,1.0550,0.0230,0.0456,0.1120,0.0400,0.0660,0.3690]
I want to take the sum of row 2: until row 1 contains 1.
for example: 0.0220+0.3110, 0.0230 + 1.0550 + 0.0230 +0.0456
I tried to do this with a loop but it doesn't give me want I want.
for i = Row1
if(i == 0)
sum(Row2)
break;
end
if(i == 1)
break;
end
end
can anyone help me with this?
Thanks a lot!

採用された回答

Image Analyst
Image Analyst 2022 年 2 月 14 日
Try using find():
Row1 =[0,0,1,0,0,0,1,0,0,1,0];
Row2 = [0.0220,0.3110,0.0230,1.0550,0.0230,0.0456,0.1120,0.0400,0.0660,0.3690];
oneIndexes = find(Row1 == 1)
oneIndexes = 1×3
3 7 10
% Find out where each stretch starts and stops.
startIndexes = [1, oneIndexes]
startIndexes = 1×4
1 3 7 10
stopIndexes = [oneIndexes - 1, length(Row2)]
stopIndexes = 1×4
2 6 9 10
% Loop over each stretch, computing the sum in that stretch.
for k = 1 : length(startIndexes)
index1 = startIndexes(k);
index2 = stopIndexes(k);
theSums(k) = sum(Row2(index1 : index2));
end
theSums % Show in command window
theSums = 1×4
0.3330 1.1466 0.2180 0.3690
  2 件のコメント
Iris Willaert
Iris Willaert 2022 年 2 月 17 日
Briliant that did the job for me!
Thanks!
Image Analyst
Image Analyst 2022 年 2 月 17 日
You're welcome. Can you click the "Accept this answer" link for the best answer and click the Vote icon for both answers. 🙂

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

その他の回答 (1 件)

David Hill
David Hill 2022 年 2 月 14 日
編集済み: David Hill 2022 年 2 月 14 日
m= [0,0,1,0,0,0,1,0,0,1;0.0220,0.3110,0.0230,1.0550,0.0230,0.0456,0.1120,0.0400,0.0660,0.3690];
%rows of the same matrix must be the same size
f=[1,find(m(1,:))];
for k=2:length(f)
s(k-1)=sum(m(2,f(k-1):f(k)-1));
end
  1 件のコメント
Iris Willaert
Iris Willaert 2022 年 2 月 17 日
Great! thanks a lot!!!

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by