Subtracting within a Matrix

2 ビュー (過去 30 日間)
Dan Lynn
Dan Lynn 2015 年 10 月 13 日
編集済み: Star Strider 2015 年 10 月 13 日
I have this matrix:
1 0
1 2
1 3
2 3
2 4
3 1
3 6
In the second column, I need to find the highest and lowest number that are associated with the same number in the first column, and then subtract the two. In row 1, the numbers 1 and 0 exist. In row 3, the numbers 1 and 3 exists. I need to subtract the 3 and the 0 and get 3 as my output.
The output should be a matrix that looks like this:
1 3
2 1
3 5
Also if a number in the first column only occurs once
1 0
1 2
1 3
2 3
2 4
3 1
3 6
4 5
Then the number in the second column associated with it in the output matrix should be a 0.
1 3
2 1
3 5
4 0

採用された回答

Joseph Cheng
Joseph Cheng 2015 年 10 月 13 日
you can use the built in function unique to determine this:
A =[ 1 0; 1 2; 1 3; 2 3; 2 4; 3 1; 3 6; 4 5]
[c1,ia1,ic1] = unique(A(:,1));
for ind = 1:length(c1)
tempMIN = min(A(ind==A(:,1),2));
tempMAX = max(A(ind==A(:,1),2));
tostore = tempMAX-tempMIN
end
also you maybe able to do this simpler with accumarray().

その他の回答 (1 件)

Star Strider
Star Strider 2015 年 10 月 13 日
編集済み: Star Strider 2015 年 10 月 13 日
The accumarray approach:
M = [ 1 0
1 2
1 3
2 3
2 4
3 1
3 6
4 5];
Mu = unique(M(:,1));
R = accumarray(Mu, Mu, [], @(x)[max(M(M(:,1)==Mu(x),2))-min(M(M(:,1)==Mu(x),2))]);
Result = [Mu R]
Result =
1 3
2 1
3 5
4 0

カテゴリ

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