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

戏子无情 提交于 2019-12-17 04:08:40

问题


I'm trying to vectorize the following MATLAB operation:

Given a column vector with indexes, I want a matrix with the same number of rows of the column and a fixed number of columns. The matrix is initialized with zeroes and contains ones in the locations specified by the indexes.

Here is an example of the script I've already written:

y = [1; 3; 2; 1; 3];
m = size(y, 1);

% For loop
yvec = zeros(m, 3);
for i=1:m
    yvec(i, y(i)) = 1;
end

The desired result is:

yvec =

 1     0     0
 0     0     1
 0     1     0
 1     0     0
 0     0     1

Is it possible to achieve the same result without the for loop? I tried something like this:

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

but it doesn't work.


回答1:


Two approaches you 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)



回答2:


Yet another approach:

yvec = full(sparse(1:numel(y),y,1));



回答3:


You could do this with accumarray:

yvec = accumarray([(1:numel(y)).' y], 1);



回答4:


I did it this way:

classes_count = 10;
sample_count = 20;
y = randi([1 classes_count], 1, sample_count); 

y_onehot = zeros(classes_count, size(y, 2));
idx = sub2ind(size(y_onehot), y, [1:size(y, 2)]);
y_onehot(idx) = 1


来源:https://stackoverflow.com/questions/23078287/create-a-zero-filled-2d-array-with-ones-at-positions-indexed-by-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!