Changing multiple columns of a matrix in relation to the sorted indexes of its specific columns

Let's say I have a 2 by 9 matrix. I want to replace 2 by 3 matrices inside this matrix with respect to the descending element type a(2,3)

, a(2,6)

and a(2,9)

. For example:

a =

    0.4    0.4   0.5   0.6   0.2  0.2  0.6  0.2  0.6
    0.5    0.8   0.9   0.9   0.6  0.6  0.1  0.2  0.8

[b i] = sort(a(2,3:3:end),2,'descend')

b =

    0.9    0.8    0.6


i =

     1     3     2

      

So, I want to have the following matrix:

a = 

0.4  0.4  0.5  0.6  0.2  0.6  0.6  0.2  0.6

0.5  0.8  0.9  0.1  0.2  0.8  0.9  0.6  0.6

      

+3


source to share


3 answers


Try converting to a matrix of cells first and then using i

rearrange cells

[b i] = sort(a(2,3:3:end),2,'descend')

A = mat2cell(a, 2, 3*ones(1,3));
cell2mat(A(i))

      

If for some reason you don't want to convert everything a

to a matrix of cells, you can do so by extending the indexing vector i

to index all columns. In your case, you will need:

I = [1,2,3,7,8,9,4,5,6]

      

which you could generate with a loop, or use bsxfun

to get



[1  7  4
 2  8  5
 3  9  6]

      

and then "flatten" using reshape

:

I = reshape(bsxfun(@plus, 3*s-2, (0:2)'), 1, [])

      

and then finally

a(:,I)

      

+4


source


Usually, when a 2d matrix is ​​split into blocks, it is better to use more dimensions:

a=reshape(a,size(a,1),3,[]);

      

Now you can access each block via a(:,:,1)

To sort use:



[~,idx]=sort(a(2,3,:),'descend')
a=a(:,:,idx)

      

If you really want a 2d matrix, change it:

a=reshape(a,2,[])

      

+1


source


sortrows

based approach:

n = 3; %// number of columns per block
m = size(a,1);
a = reshape(sortrows(reshape(a, m*n, []).', -m*n).', m, []);

      

It works by changing every block in a row, sorting the rows by the last column, and changing the shape.

0


source







All Articles