Script file that sums values and checks against another vector?

2 views (last 30 days)
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.

Answers (1)

Jan
Jan on 31 Jan 2018
Edited: Jan on 31 Jan 2018
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.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!