简体   繁体   中英

Create new matrix with ranks of elements of other matrix, MATLAB

I have a matrix for example

A = [21 3 14;0 1 5;8 2 4]

and want a new matrix

B =[9 4 8;1 2 6;7 3 5]

I found a method for creating a vector

http://blogs.mathworks.com/loren/2007/08/21/reversal-of-a-sort/#7

but is there a function for matrix?

Thanks

Similar to abhineetprasad's solution, but you don't need a key–value structure.

You can use almost the same method for matrices as for vectors. You just need to determine the sort indices for A with respect to the vector-shaped version A(:) and initialize B to the same dimensions as A. Then you can use linear indexing into the matrix B to fill it with the ranks:

% prepare matrix B with the same dimensions as A
B = zeros(size(A));
% determine sort indices of the matrix entries treated as a vector
[~, ind] = sort(A(:));
% use linear indexing by sort indices to fill vector B with ranks
B(ind) = 1 : numel(B);

A possible way of doing this would be:

  1. Read the matrix into a vector.
  2. Use the link you've found to sort the vector.
  3. Store the vector as Map with vector value as the "key" and vector index as the value.
  4. Populate the new matrix by looking up the index of the numbers as you read the first matrix again using the map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM