创建一个零填充的二维数组,其中一个位于由向量索引的位置 [英] Create a zero-filled 2D array with ones at positions indexed by a vector
本文介绍了创建一个零填充的二维数组,其中一个位于由向量索引的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对以下 MATLAB 操作进行矢量化:
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
想要的结果是:
yvec =
1 0 0
0 0 1
0 1 0
1 0 0
0 0 1
是否可以在没有 for 循环的情况下实现相同的结果?我试过这样的事情:
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;
但它不起作用.
推荐答案
您可以在这里使用两种方法.
Two approaches you can use here.
方法 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)
这篇关于创建一个零填充的二维数组,其中一个位于由向量索引的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文