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

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]

7 Comments

@Yuvaraj V: you have really specified how to generate the outpour matrix from the input vector. What would you expect the output from this vector to be?:
A = [5,1,1,4]
@Yuvaraj V: thank you, that is clearer now for me. For a simple solution see my answer.
@Stephen Cobeldick: For your 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
@Yuvaraj V: you are changing your specification. First you wrote a comment where you stated that my example was not possible because 5 is larger than numel(A). Now you have deleted that comment and decided that it is possible. Please clarify which is the correct specification.
@Stephen Cobeldick: yes. your answer is working. Thank you.
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.
@Yuvaraj V: I have updated my answer to match your comment.
@Stephen Cobeldick: Thank You so much

Sign in to comment.

 Accepted Answer

>> 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

More Answers (1)

Birdman
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

2 Comments

@Birdman: there is a syntax error on this line:
Ans=zeros(max(size(A));
Birdman
Birdman on 6 Jun 2018
Edited: Birdman on 6 Jun 2018
Yes there should be one more parenthesis. Thanks.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!