How can I convert a numeric matrix(a) to a 0 and 1 matrix(b)?

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.

 채택된 답변

Geoff Hayes
Geoff Hayes 2014년 4월 25일
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

댓글 수: 5

Thanks Geoff
You saved me!
I've modified "b=zeros(r,r)" to "b=zeros(r,4)" to avoid of creating more zero columns.
Glad to help!
Geoff, one more question,
I added a second column to the matrix "a":
a = [3 2;1 1;4 2;2 1]
Then I want matrix "b" to be:
b = [0 0 0 0;0 0 1 0;1 0 0 0;0 0 0 0;0 0 0 0;0 0 0 1;0 1 0 0;0 0 0 0]
In other words, each row in matrix "a" converted to two rows (0/1) in matrix "b" with this condition:
if a(1,2)=1
goes to the first row in matrix "b"
but, if a(1,2)=2
goes to the second row in matrix "b"
Other things same as last loop.
Thank you.
Hi Mohammed,
So this isn't much different from before - your b now has 8 rows (since a has 4 rows) and all rows of b are paired. The first row of a either populates row 1 or row 2 of b, the second row of a populates either row 3 or row 4 of b, etc. with the ith row of a populating either row 2i-1 or 2i of b:
for i=1:r
if a(i,2)==1
b(2*i-1,a(i,1))=1;
else
b(2*i,a(i,1))=1;
end
end
That should do it!
Geoff
Thanks Geoff, It was great and worked very well.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jos (10584)
Jos (10584) 2014년 4월 25일
No need for for-loops. This shows the power of linear indexing:
a = [3 1 4 2] % these specify column indices
b = zeros(numel(a), max(a))
idx = sub2ind(size(b), 1:numel(a), a(:).') % linear indices
b(idx) = 1
As for your second question:
a = [3 2; 1 1; 4 2; 2 1]
b = zeros(2*size(a,1), max(a(:,1)))
colix = a(:,1).'
rowix = 2*(1:size(a,1)) - (a(:,2)==1).'
idx = sub2ind(size(b), rowix, colix)
b(idx) = 1

댓글 수: 1

Thanks a lot Jos. You used a professional level of coding in Matlab.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

Moe
2014년 4월 25일

댓글:

Moe
2014년 4월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by