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

1 次查看(过去 30 天)
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 个评论
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by