创建一个零填充的2D数组,该数组在矢量索引的位置处带有一个 [英] Create a zero-filled 2D array with ones at positions indexed by a vector
本文介绍了创建一个零填充的2D数组,该数组在矢量索引的位置处带有一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对以下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)
这篇关于创建一个零填充的2D数组,该数组在矢量索引的位置处带有一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文