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
Post a Comment