Sum values from one column vector based on another column vector

3 ビュー (過去 30 日間)
Allison Sims
Allison Sims 2022 年 7 月 4 日
コメント済み: Allison Sims 2022 年 7 月 4 日
How do I compute this without using any loops or conditionals?
I want to sum the values in column B based on if the value in column A is a 1
So for example I want to add 34 and 28 only and save it to a new variable
A B
1 34
2 78
4 3
1 28

採用された回答

DGM
DGM 2022 年 7 月 4 日
編集済み: DGM 2022 年 7 月 4 日
Assuming A and B are different variable names with the same length:
A = [1; 2; 4; 1];
B = [34; 78; 3; 28];
mysum = sum(B(A==1),'all')
mysum = 62
Assuming they're both columns in the same array:
A = [1 34; 2 78; 4 3; 1 28];
mysum = sum(A(A(:,1)==1,2),'all')
mysum = 62

その他の回答 (0 件)

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by