How can I add this condition on my code?

조회 수: 1 (최근 30일)
Uche
Uche 2023년 3월 7일
댓글: Uche 2023년 3월 8일
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에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by