Creating an mn matrix from 0s and 1s from a m-size vector of column indices

I have an m-dimensional vector of integers from 1 to n. These integers are column indices for the m × n matrix.

I want to create an m × n matrix from 0s and 1s, where in the mth row there is 1 in the column that is given by the mth value in my vector.

Example:

% my vector (3-dimensional, values from 1 to 4):
v = [4;
     1;
     2];

% corresponding 3 × 4 matrix
M = [0 0 0 1;
     1 0 0 0;
     0 1 0 0];

Is this possible without a for loop?

+5
source share
3 answers

Of course, why did they come up with sparse matrices:

>> M = sparse(1:length(v),v,ones(length(v),1))
M =

   (2,1)        1
   (3,2)        1
   (1,4)        1

which you can convert to a full matrix if you want with full :

>> full(M)
ans =

     0     0     0     1
     1     0     0     0
     0     1     0     0
+4
source

Or without a sparse matrix:

>> M = zeros(max(v),length(v));
>> M(v'+[0:size(M,2)-1]*size(M,1)) = 1;
>> M = M'

M =

 0     0     0     1
 1     0     0     0
 0     1     0     0

Transposition is used because Matlab matrices are addressed by columns

+3
source

In Octave, at least since 3.6.3, you can easily do this using translation:

M = v==1:4
+3
source

All Articles