MATLAB: Use a vector to populate columns in a matrix.

classificationvectorization

I have a vector of length m with possible values 1-10 for each element. I want a matrix that is m x 10 with ones in columns corresponding to the elements of the vector. Is there a way to vectorize this loop?
for i = 1:m
y_big(i,y(i))=1;
end
Example:
y = [4, 8, 1]
m = size(v, 2)
I want to get:
y_big = [0 0 0 1 0 0 0 0 0 0;
0 0 0 0 0 0 0 1 0 0;
1 0 0 0 0 0 0 0 0 0]

Best Answer

I'm reinventing sub2ind, Convert subscripts to linear indices ;-) See also ind2sub, Subscripts from linear index. &nbsp (I replaced v by y, since I assume it's a typo.)
y = [4, 8, 1];
m = size( y, 2 );
y_big = zeros( m, 10 );
y_big( ((y-1)*m + 1) + (0:1:m-1) ) = 1;
Inspect result
>> y_big
y_big =
0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
1 0 0 0 0 0 0 0 0 0
Or using sub2ind
y_big = zeros( m, 10 );
y_big( sub2ind( size(y_big), [1:m], y ) ) = 1;
However, don't take for granted that this is "better" and faster than your for-loop.