Matrix value to store as matrix index
Show older comments
Hello All,
I have a matrix A and I would like its values to be stored as its indeces in another matrix
A = [2 2 1 1 1; 3 3 3 0 2; 5 4 5 0 3]
A =
2 2 1 1 1
3 3 3 0 2
5 4 5 0 3
% the result matrix AA should look like:
AA =
0 0 1 1 1
2 2 0 0 2
3 3 3 0 3
0 4 0 0 0
5 0 5 0 0
you see how the 2 at A11 shows up on AA21 (because 2 is the second index in the first column) and 5 shows up on the fifth row (AA51). Anyhelp would be appreciated. Thnx
Accepted Answer
More Answers (2)
Andrei Bobrov
on 6 Jan 2019
ii = (1:5)';
AA = any(ii == permute(A,[3,2,1]),3).*ii;
2 Comments
Stephen23
on 6 Jan 2019
+1 neat idea. Requires R2016b or later.
Andrei Bobrov
on 6 Jan 2019
Thank you Stephen!
For old MATLAB ( <= R2016a)
AA = any(bsxfun(@eq,ii,permute(A,[3,2,1])),3).*ii;
Without loops, works for any version:
A = [2,2,1,1,1;3,3,3,0,2;5,4,5,0,3]
S = size(A);
C = repmat(1:S(2),S(1),1);
Z = zeros(max(A(:)),S(2));
X = A>0;
Y = sub2ind(size(Z),A(X),C(X));
Z(Y) = A(X)
Giving:
Z =
0 0 1 1 1
2 2 0 0 2
3 3 3 0 3
0 4 0 0 0
5 0 5 0 0
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!