Matrix value to store as matrix index

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

2 Comments

What happens to A11 ?
A11 value is two so --> in AA it should be in row two

Sign in to comment.

 Accepted Answer

Rik
Rik on 6 Jan 2019
Edited: Rik on 6 Jan 2019
The code below works. I'll try to find a better way, but in the meantime you can use this.
A = [2 2 1 1 1; 3 3 3 0 2; 5 4 5 0 3];
AA=zeros(max(A(:)),size(A,2));
for r=1:size(A,1)
for c=1:size(A,2)
if A(r,c)~=0
AA(A(r,c),c)=A(r,c);
end
end
end
disp(AA)
And this is my try without loops:
A = [2 2 1 1 1; 3 3 3 0 2; 5 4 5 0 3];
sz=[max(A(:)),size(A,2)];
rowval=A;rowval(rowval==0)=NaN;
colval=(1:sz(1)).*ones(size(A,1),1);
%or on older releases (before R2016b):
%colval=bsxfun(@mtimes,1:sz(1),ones(size(A,1),1));
subs=[rowval(:),colval(:)];
subs(isnan(subs(:,1)),:)=[];
AA=accumarray(subs,val,sz,[],0);
disp(AA)

More Answers (2)

ii = (1:5)';
AA = any(ii == permute(A,[3,2,1]),3).*ii;

2 Comments

+1 neat idea. Requires R2016b or later.
Thank you Stephen!
For old MATLAB ( <= R2016a)
AA = any(bsxfun(@eq,ii,permute(A,[3,2,1])),3).*ii;

Sign in to comment.

Stephen23
Stephen23 on 6 Jan 2019
Edited: Stephen23 on 6 Jan 2019
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

Asked:

on 6 Jan 2019

Commented:

on 7 Jan 2019

Community Treasure Hunt

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

Start Hunting!