SUM of selected elements in Matrix

1 回表示 (過去 30 日間)
ANAND ASP
ANAND ASP 2020 年 11 月 20 日
コメント済み: Ameer Hamza 2020 年 11 月 20 日
i have matrix
M = [1 1 2 60;
2 3 2 90;
3 1 3 240;
4 2 3 200;
5 3 3 160]
i want to select 1 from 2nd column and acoording to that i want to SUM of 60 and 240. same way i want to select 3 from 2nd column and SUM of 90 and 160.
how to creat?

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 11 月 20 日
編集済み: Ameer Hamza 2020 年 11 月 20 日
Are you looking for something like this
M = [1 1 2 60;
2 3 2 90;
3 1 3 240;
4 2 3 200;
5 3 3 160];
result = splitapply(@sum, M(:,4), M(:,2))
Result
>> result
result =
300
200
250
  2 件のコメント
ANAND ASP
ANAND ASP 2020 年 11 月 20 日
yes exactly, thank you so much...
could you pass formula for subtraction
i want to select 2 from 2nd column and 3rd column and i want
sum like : + 200
- 60
- 90
= 50
Ameer Hamza
Ameer Hamza 2020 年 11 月 20 日
In that case, you can just use logical indexing
M = [1 1 2 60;
2 3 2 90;
3 1 3 240;
4 2 3 200;
5 3 3 160];
idx1 = M(:,2)==2;
idx2 = M(:,3)==2;
result = sum(M(idx1,4))-sum(M(idx2,4))

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by