필터 지우기
필터 지우기

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

카테고리

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