Converting an integer to a vector of 0's and single 1

138 Views Asked by At

I have an array of labels in the form:
[1;3;2;]
I wish to convert this to an array of vectors, where only the i'th element is 1, and the rest are 0's.
So the above would be (assuming 5 lables):
[1 0 0 0 0]
[0 0 1 0 0]
[0 1 0 0 0]

How can this be done, without a 'for' loop?

2

There are 2 best solutions below

1
On

What is wrong with just doing it? Let L be the length of the array. Dimension A(L,5). Set all elements of A to zero. Then go through the array, in your example set A(1,1)=1, A(2,3)=1, A(3,2)=1 where the first index just counts from 1 to L and the second is the value in that position.

0
On

Here is how you can do this in Matlab:

maxLabel = 5;
x = [1; 3; 2];
M = zeros(length(x),maxLabel);
idx = sub2ind(size(M), 1:numel(x),x)
M(idx) = 1;

Or more compact for your specific case:

M = zeros(3,5);
M(sub2ind([3 5], 1:3,[1;3;2]))