how can I rearrange columns of a matrix according to another index matrix
2 views (last 30 days)
Show older comments
I have a 2 by 3 matrix
A= [32, 9, 43 ; 6, 4, 7];
and a 2 by 3 index matrix:
Ind=[1,3,2 ; 2,3,1];
I would like to arrange each row of A according to the index of each row of Ind. That is, I want to get a matrix B, whose first row is arranged according to the first row of Ind:
[32, 43, 9]
and the second row is arranged according to the second row of Ind:
[4, 7, 6]
So
B= [32, 43, 9 ; 4, 7, 6]
What should i do ? many thanks ! (sorry, i forgot to say that i'd like to avoid using loops)
0 Comments
Answers (1)
Kevin Phung
on 22 Mar 2021
Edited: Kevin Phung
on 22 Mar 2021
A= [32, 9, 43 ; 6, 4, 7];
Ind=[1,3,2 ; 2,3,1];
B = nan(size(A));
for i = 1:size(A,1)
B(i,:) = A(i,Ind(i,:))
end
3 Comments
Image Analyst
on 22 Mar 2021
I don't think so unless you have a 1-D vector. Maybe you could do it with ind2subs() and subs2ind() but it would be way more complicated than a simple for loop. For an array this microscopic you should just use for loops. Unless you're having more than 10 or 20 million iterations, the for loop will take just a fraction of a second. How many columns and rows do you expect your arrays to be? If you have hundreds of millions or billions of elements, we may need to see if some non-for loop way is faster.
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!