Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...