Script file that sums values and checks against another vector?

조회 수: 1 (최근 30일)
Isaac Al-rai
Isaac Al-rai 2018년 1월 31일
편집: Jan 2018년 1월 31일
Hello, I am trying to perform a script file that executes a sum and check loop. I need to write a script such that it reads the values in x and sums them until the sum value exceeds n, where n assumes one at a time the values contained in the array: n = [65 156 187 42]. Store all the calculated sums (for each n) in a single array A.
I tried entering the following but am not sure this is correct.
if true
% code
end
x=HW1Rand;
r=0;
n=[65 156 187 42];
for ii=1:length(x)
for jj=length(n)
r=r+ii;
if r>n
Solution=n(jj);
break
end
end
end
HW1Rand is a 1x20 random vector. I am not sure If this is actually checking each individual values of n and breaking at that point and I still need to store this in a single array A. Is there anything I can do to make this work better? Apologies if the syntax is messy.

답변 (1개)

Jan
Jan 2018년 1월 31일
편집: Jan 2018년 1월 31일
x = HW1Rand;
sumx = cumsum(x); % Calculate the sum once only
n = [65 156 187 42];
Solution = nan(1, length(n)); % Pre-allocate
for jj = 1:length(n)
index = find(sumx > n(jj), 1, 'first');
if ~isempty(index)
Solution(jj) = sumx(index);
end
end
It is cheaper to calculate the cumulative sum once only. Then you can use find() instead of using a loop. Solution is pre-allocated with NaNs, because it is possible, that no elemen of sumx is larger than the current element of n.

카테고리

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