Azzera filtri
Azzera filtri

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

1 visualizzazione (ultimi 30 giorni)
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!

Risposta accettata

Image Analyst
Image Analyst il 14 Feb 2022
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 Commenti
Iris Willaert
Iris Willaert il 17 Feb 2022
Briliant that did the job for me!
Thanks!
Image Analyst
Image Analyst il 17 Feb 2022
You're welcome. Can you click the "Accept this answer" link for the best answer and click the Vote icon for both answers. 🙂

Accedi per commentare.

Più risposte (1)

David Hill
David Hill il 14 Feb 2022
Modificato: David Hill il 14 Feb 2022
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

Prodotti


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by