How to convert row to matrix with below format????

4 views (last 30 days)
Yuvaraj V on 6 Jun 2018
Commented: Yuvaraj V on 6 Jun 2018
I need to convert row to matrix. For example, A=[1 2 3 4 5]
Need answer like this, Ans=[1 0 0 0 0; 0 1 0 0 0; 0 0 1 0 0; 0 0 0 1 0; 0 0 0 0 1]

Yuvaraj V on 6 Jun 2018
Also, I have doubt from your question.
If input A=[5,1,1,4], the output like this,
0 0 0 0 1
1 0 0 0 0
1 0 0 0 0
0 0 0 1 0
Help me sir.
Stephen Cobeldick on 6 Jun 2018
Yuvaraj V on 6 Jun 2018
@Stephen Cobeldick: Thank You so much

Stephen Cobeldick on 6 Jun 2018
Edited: Stephen Cobeldick on 6 Jun 2018
>> A = [3,1,1,4];
>> N = numel(A);
>> Z = zeros(N);
>> Z(sub2ind([N,N],1:N,A)) = 1
Z =
0 0 1 0
1 0 0 0
1 0 0 0
0 0 0 1
EDIT: if my example is acceptable, as you now write, then you will need something like this:
>> A = [5,1,1,4];
>> R = numel(A);
>> C = max(A);
>> Z = zeros(R,C);
>> Z(sub2ind([R,C],1:R,A)) = 1
Z =
0 0 0 0 1
1 0 0 0 0
1 0 0 0 0
0 0 0 1 0

1 Comment

Yuvaraj V on 6 Jun 2018
@Stephen Cobeldick: Thank You so much

Birdman on 6 Jun 2018
Edited: Birdman on 6 Jun 2018
Something like this should work:
A=[3 1 1 4];
Ans=zeros(max(size(A)));
r=1:max(size(A));
c=A;
idx=sub2ind(size(repmat(A,max(size(A)),1)),r,c);
Ans(idx)=1