matlab - Create a zeros filled 2D array with ones at positions indexed by a vector -


i'm trying vectorize following matlab script:

given column vector indexes, want matrix same number of rows of column , fixed number of columns. matrix initialized zeros , contains ones in locations specified indexes.

here example of script i've written:

y = [1; 3; 2; 1; 3]; m = size(y, 1);  % loop yvec = zeros(m, 3); i=1:m     yvec(i, y(i)) = 1; end 

the (correct) result is:

yvec =   1     0     0  0     0     1  0     1     0  1     0     0  0     0     1 

is possible achieve same result without for loop?

i trying like:

% vectorization (?) yvec2 = zeros(m, 3); yvec2(:, y(:)) = 1; 

but not working...

thanks!

two approaches can use here.

approach 1:

y = [1; 3; 2; 1; 3]; yvec = zeros(numel(y),3); yvec(sub2ind(size(yvec),1:numel(y),y'))=1 

approach 2 (one-liner):

yvec = bsxfun(@eq, 1:3,y) 

Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -