Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
Iris Willaert
Iris Willaert le 14 Fév 2022
Commenté : Image Analyst le 17 Fév 2022
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!

Réponse acceptée

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

Connectez-vous pour commenter.

Plus de réponses (1)

David Hill
David Hill le 14 Fév 2022
Modifié(e) : David Hill le 14 Fév 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

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by