Convert a vector to a binary matrix
Show older comments
y = [1; 1; 2; 3; 4; 4];
I want to convert this to a matrix such that in each row the corresponding element is 1 and the rest are zero.
y = [1 0 0 0;
1 0 0 0;
0 1 0 0;
0 0 1 0;
0 0 0 1];
What is the best way to do this preferably without using loops?
Accepted Answer
More Answers (1)
Pawel Jastrzebski
on 2 Jan 2018
Edited: Pawel Jastrzebski
on 2 Jan 2018
With LOOP:
y = [1; 1; 2; 3; 4; 4];
nRow = length(y);
nCol = max(y);
A = zeros(nRow,nCol);
for i=1:nRow
A(i,y(i)) = 1;
end
A
WITHOUT LOOP:
y1 = [1; 1; 2; 3; 4; 4];
nRow1 = length(y1);
nCol1 = max(y1);
A1 = zeros(nRow1,nCol1);
index = (y1-1).*nRow1+(1:nRow1)';
A1(index) = 1;
A1
2 Comments
Birdman
on 2 Jan 2018
What is the best way to do this preferably without using loops?
Do not use loop.
Utkarsh Barsaiyan
on 2 Jan 2018
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!