Question about logical calculation in matrix

4 ビュー (過去 30 日間)
kingsley
kingsley 2017 年 9 月 26 日
編集済み: Jan 2017 年 9 月 26 日
I want to sum up the numbers on the 1st column if its corresponding numbers on the 2nd column =1; and if sum up the numbers on the 1st column if its corresponding numbers on the 2nd column =2; The answer should be r1=0.5 r2=1.4 I don't know where I made mistakes. Here is the code I have so far. PLEASE HELP ME OUT。
AA=[0.2 1;0.3 1;0.5 2;0.9 2];
for i = 1:4
if AA(i,2)<2
r1=zeros(1);
r1=r1+AA(i,1);
else
r2=zeros(i,1);
r2=r2+AA(i,1)
end
end

採用された回答

Jan
Jan 2017 年 9 月 26 日
編集済み: Jan 2017 年 9 月 26 日
The mistake is the zeros inside the loop, which resets the counter repeatedly:
AA = [0.2 1; 0.3 1; 0.5 2; 0.9 2];
r1 = 0; % BEFORE the loop
r2 = 0;
for i = 1:4
if AA(i,2)<2
r1 = r1 + AA(i,1);
else
r2 = r2 + AA(i,1);
end
end
Or smarter without a loop:
match = (A(:, 2) == 1);
r1 = sum(A(match, 1));
r1 = sum(A(~match, 1));

その他の回答 (1 件)

Stephen23
Stephen23 2017 年 9 月 26 日
編集済み: Stephen23 2017 年 9 月 26 日
Just use accumarray:
>> AA = [0.2,1;0.3,1;0.5,2;0.9,2]
AA =
0.20000 1.00000
0.30000 1.00000
0.50000 2.00000
0.90000 2.00000
>> accumarray(AA(:,2),AA(:,1))
ans =
0.50000
1.40000
>>

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by