Script file that sums values and checks against another vector?

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