Given a matrix A, and a matrix of column indices B, how to create a new matrix C from A and B

1 view (last 30 days)
Consider the following 3 x 3 matrix A:
5 8 3
4 8 1
9 6 8
Consider the following 3 x 3 matrix B:
3 1 2
2 3 1
1 3 2
The rows of B contain the desired indexes of the rows of A. My goal is to create the matrix C:
3 5 8
8 1 4
9 8 6
So the rows of A are reshuffled according the indices in B. Any ideas on how to do this, preferably without loops?

Accepted Answer

Jos (10584)
Jos (10584) on 19 Mar 2014
A = [ 5 8 3
4 8 1
9 6 8 ]
B = [3 1 2
2 3 1
1 3 2]
% B is an array of column indices
% create the corresponding array of row indices
R = repmat(1:size(B,1),size(B,2),1).'
% the subindices (R,B) are to be transformed into linear indices
idx = sub2ind(size(A),R,B)
% which we can use to retrieve the values from A
C = A(idx)

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!