How can I add this condition on my code?

1 Ansicht (letzte 30 Tage)
Uche
Uche am 7 Mär. 2023
Kommentiert: Uche am 8 Mär. 2023
Good evening,
Please can someone help with this scenario:
I have two column vectors as seen in the code. I want to succesively add the elements in the first column. However, each time the sum is a multiple of 100, I want to identify the point, and hold the corresponding element on the second column. These points from the second column will be added up and displayed.
For example, on this code, after adding 10+20+30+40 = 100 on the first column, the condition multiple of 100 is met. The element corresponding to this point on the second column is 5. Store this number to variable X. Continuing the addition of the first column elements, 10+20+30+40 +5= 105, the condition is not met, nothing happens to X. Back to first column, 10+20+30+40+5+60+40=205, the condition is met, and from second column X = 4+ 8, and just like that until we add up all the first column element. For this case, X should be X = 4+8+10+1=23
U = [10;20;30;40;5;60;40;80;20;100];
V = [2;3;4;5;6;7;8;9;10;1];
W = 0;
X = 0;
for i = 1:length(U)
W = W + U(i);
if W = 100
X = X + V(i);
end
end
disp(X)

Akzeptierte Antwort

Voss
Voss am 7 Mär. 2023
Bearbeitet: Voss am 7 Mär. 2023
U = [10;20;30;40;5;60;40;80;20;100];
V = [2;3;4;5;6;7;8;9;10;1];
idx = find(diff([0;floor(cumsum(U/100))]))
idx = 4×1
4 7 9 10
V(idx)
ans = 4×1
5 8 10 1
sum(V(idx))
ans = 24

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by