MATLAB: How to convert a numeric matrix(a) to a 0 and 1 matrix(b)

for loopwhile loop

Hi everyone,
suppose I have a matrix:
a = [3;
1;
4;
2]
Then I want it to be:
b = [0 0 1 0;
1 0 0 0;
0 0 0 1;
0 1 0 0]
Explanation of first row in matrix "b" (how it's created, manual):
if a(1)=1
b(1,1)=1
elseif b(1,1)=0
end
if a(1)=2
b(1,2)=1
elseif b(1,2)=0
end
if a(1)=3
b(1,3)=1
elseif b(1,3)=0
end
if a(1)=4
b(1,4)=4
elseif b(1,4)=0
end
and so on for rows 2,3 and 4 in matrix a.
I'm looking for a automatic loop or function in the Matlab, because real size of matrix a is 1000 rows.
Please help me, Thanks.

Best Answer

Hi Mohammed,
Why not just use a simple loop?
r=size(a,1); % get the number of rows in a (first dimension,1)
b=zeros(r,r); % initialize the b matrix to all zeros
for i=1:r
b(i,a(i))=1; % set the ith row of b with the a(i) column set to one
end
Geoff