如何在 Matlab 中对以下代码进行矢量化?

How can I vectorize the following piece of code in Matlab?

y 是包含数字 1 到 10 的 5000 x 1 向量。我可以将 y 转换为 Y(5000 x 10 矩阵),这样

Y = zeros(5000,10);
for i = 1:5000
    Y(i,y(i))=1;
end

不使用 for 循环是否可以达到相同的结果?

你可以使用 sparse

y = [8 5 7 4 2 6 4]; % example y. Arbitrary size
M = 10; % maximum possible value in y
Y = full(sparse(1:numel(y), y, 1, numel(y), M));

等价于accumarray:

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

除了@LuisMendo 的回答,你还可以使用sub2ind:

Y = zeros(5,10);                      % Y preallocation, zeros(numel(y),max_column)
y = [8 5 7 4 2];                      % Example y
Y(sub2ind(size(Y),1:numel(y),y)) = 1  % Linear indexation

注意到如果存在重复的 [row,column] 索引对,此方法与 accumarraysparse 略有不同:

% The linear index assigns the last value:
Y = zeros(2,2);
Y(sub2ind(size(Y),[1 1],[1,1])) = [3,4] % 4 overwrite 3

结果:

Y =

   4   0
   0   0

VS

% Sparse sum the values:
Y = full(sparse([1 1],[1,1], [3,4], 2, 2)) % 3+4

结果:

Y =

   7   0
   0   0

使用implicit expansion的解决方案:

Y = y == 1:10;

它创建了一个逻辑矩阵。如果你需要一个双矩阵你可以写:

Y = double(y == 1:10);