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
source to share
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)
source to share