How can I add this condition on my code?

2 次查看(过去 30 天)
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)

采纳的回答

Voss
Voss 2023-3-7
编辑:Voss 2023-3-7
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by