フィルターのクリア

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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by