Add the rows of a Matrix until a certain value.

4 ビュー (過去 30 日間)
Ellie
Ellie 2015 年 12 月 23 日
コメント済み: Walter Roberson 2015 年 12 月 23 日
Hi All, I have this code which will add values in a vector until a certain value and then give the corresponding location. However I would like to modify this so that it would work with a matrix. Here is the current code.
A=[3 4 10 3 9 10 12 4 11 9 11 10]';
sum1=0;
k=1;
while sum1<15
sum1=sum1+A(k);
k=k+1;
end
sum1
k = k-1;
Now the output is sum1=17 and k = 3. If A instead was A=[3 4 10 3 9 10; 12 4 11 9 11 10], then ideally the output would be sum1 = 17 16 and k = 3 2
Any help would be appreciated.

採用された回答

Guillaume
Guillaume 2015 年 12 月 23 日
First, a much better way to implement your vector algorithm is to use cumsum amd find:
A = [3 4 10 3 9 10 12 4 11 9 11 10]';
sumA = cumsum(A);
k = find(sumA >= 15, 1)
sum1 = sumA(k)
You can use cumsum on a matrix to sum each row. The difficulty is that find does not work on rows, so you have to use a loop or split the rows into a cell array and use cellfun on that:
A = [3 4 10 3 9 10; 12 4 11 9 11 10];
threshold = 15;
rowsums = num2cell(cumsum(A, 2), 2);
thresholdcol = cellfun(@(row) find(row >= threshold, 1), rowsums)
thresholdsum = cellfun(@(row, k) row(k), rowsums, num2cell(thresholdcol))
  1 件のコメント
Walter Roberson
Walter Roberson 2015 年 12 月 23 日
編集済み: Walter Roberson 2015 年 12 月 23 日
Note: this code will have problems if a row does not meet the threshold.

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2015 年 12 月 23 日
cA = cumsum(A, 2);
k = reshape(sum(cA < 15,2) + 1, 1, []);
sum1 = cA(sub2ind(size(cA), 1:size(cA,1), k));
Guaranteed to break if one of the rows does not reach 15.
  1 件のコメント
Walter Roberson
Walter Roberson 2015 年 12 月 23 日
More compactly:
cA = cumsum(A, 2);
k = sum(cA < 15, 2).' + 1;
nA = size(A,1);
sum1 = cA((0:nA-1)*nA + k);

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by