How to get the highest values on a matrix depending on the values of another matrix

1 回表示 (過去 30 日間)
I want to sort out the values of a matrix (A) depending on another independent matrix (B), and create a third matrix with the results (C). See the example:
A = [1 2 1; 4 1 3; 3 8 2]
B = [1 2 3; 4 5 6; 7 8 9]
C = [5 9 5; 4 5 7; 7 8 9]
Therefore, for the same elements on A, I want to find the highest elements on B. For instance, for values of 1, I want to loop through B until finding the highest value related, that in the example is 5. Then I want to pass all the values to a new matrix C.
I have tried with generating my own functions or using loop, but I found no solution after 4 days of trying this. Would appreciate some explanation if I am missing something or not understanding the properties of matrices in Matlab, I am quite used to Python and R, but in Matlab I am a newbie.
Thanks!

採用された回答

Stephen23
Stephen23 2015 年 9 月 11 日
編集済み: Stephen23 2015 年 9 月 11 日
In just three lines, without any loops:
>> A = [1 2 1; 4 1 3; 3 8 2];
>> B = [1 2 3; 4 5 6; 7 8 9];
>> [~,~,X] = unique(A(:));
>> D = accumarray(X,B(:),[],@max);
>> C = reshape(D(X),size(A))
C =
5 9 5
4 5 7
7 8 9
  1 件のコメント
Victor Francisco Pajuelo Madrigal
Victor Francisco Pajuelo Madrigal 2015 年 9 月 11 日
Thanks for this reply! It´s simplicity helped on the large dataset that I am working on.

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

その他の回答 (1 件)

Guillaume
Guillaume 2015 年 9 月 11 日
A = [1 2 1; 4 1 3; 3 8 2];
B = [1 2 3; 4 5 6; 7 8 9];
assert(isequal(size(A), size(B)), 'matrix A and B have different size');
C = zeros(size(A)); %destination matrix
for ua = unique(A)' %iterate over the unique values of A
C(A == ua) = max(B(A == ua)); %for those value of A that are ua, update C with the max of B
end
  1 件のコメント
Victor Francisco Pajuelo Madrigal
Victor Francisco Pajuelo Madrigal 2015 年 9 月 11 日
編集済み: Victor Francisco Pajuelo Madrigal 2015 年 9 月 11 日
Thanks for the reply! The comments to the code were great to know what was going on! It worked for a small matrix but my dataset is very large (working with satellite images) and it takes a lot of CPU processing.

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

カテゴリ

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