Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 758
Muffo Avatar asked Apr 15 '14 08:04

Muffo


People also ask

How do I generate zeros and ones in Matlab?

X = zeros( sz ) returns an array of zeros where size vector sz defines size(X) . For example, zeros([2 3]) returns a 2-by-3 matrix. X = zeros(___, typename ) returns an array of zeros of data type typename . For example, zeros('int8') returns a scalar, 8-bit integer 0 .

What does ones mean in Matlab?

Description. X = ones returns the scalar 1 . example. X = ones( n ) returns an n -by- n matrix of ones. example.

What is the zeros function in Matlab?

The zeros function allows you, the programmer, to create an "empty array"... okay its not really empty, it has a bunch of zeros in it. There are two reasons to do this. You are creating a list of counters, and counting starts at 0.


2 Answers

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)
like image 178
Divakar Avatar answered Oct 24 '22 07:10

Divakar


Yet another approach:

yvec = full(sparse(1:numel(y),y,1));
like image 23
Luis Mendo Avatar answered Oct 24 '22 07:10

Luis Mendo