sum a column depending on another column

9 ビュー (過去 30 日間)
James Gooding
James Gooding 2012 年 8 月 2 日
Hi there,
I would like to sum values in a column where a criterion has been met in another column in a corresponding row of a matrix.
take the matrix:
xx 6 xx 1;
xx 9 xx 0;
xx 10 xx 1;
I want to sum the second column but only for rows where the fourth column is equal to one.
Hence, using the example, I would hope to have a solution of 16.
Any help with this simple problem is greatly appreciated.
James

採用された回答

Andrei Bobrov
Andrei Bobrov 2012 年 8 月 2 日
out = sum(A(A(:,4)~=0,2))

その他の回答 (1 件)

Conrad
Conrad 2012 年 8 月 2 日
Something like this:
% Dummy data.
A =[ NaN 6 NaN 1;...
NaN 9 NaN 0;...
NaN 10 NaN 1];
idx = A(:,4)==1;
s = sum(A(idx,2));

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by