我正在尝试矢量化以下 MATLAB 操作:
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.
这是我已经编写的脚本示例:
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
期望的结果是:
yvec =
1 0 0
0 0 1
0 1 0
1 0 0
0 0 1
不使用 for 循环是否可以达到相同的结果?我试过这样的事情:
% Vectorization (?)
yvec2 = zeros(m, 3);
yvec2(:, y(:)) = 1;
但它不起作用。
最佳答案
您可以在此处使用两种方法。
方法一:
y = [1; 3; 2; 1; 3];
yvec = zeros(numel(y),3);
yvec(sub2ind(size(yvec),1:numel(y),y'))=1
方法 2(单行):
yvec = bsxfun(@eq, 1:3,y)
关于matlab - 创建一个零填充的二维数组,其中的元素位于由向量索引的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23078287/