Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an m by n matrix of 0s and 1s from m-sized vector of column indexes

I have a m-dimensional vector of integers ranging from 1 to n. These integers are column indexes for m × n matrix.

I want to create a m × n matrix of 0s and 1s, where in m-th row there's a 1 in the column that is specified by m-th 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?

like image 656
usr Avatar asked May 19 '12 12:05

usr


People also ask

How do you turn a column vector into a matrix?

To convert a vector into matrix, just need to use matrix function. We can also define the number of rows and columns, if required but if the number of values in the vector are not a multiple of the number of rows or columns then R will throw an error as it is not possible to create a matrix for that vector.

How do I create a column vector in MATLAB?

Column vectors are created using square brackets [ ], with semicolons or newlines to separate elements. A row vector may be converted into a column vector (and vice versa) using the transpose operator '.


2 Answers

Of course, that's why they invented 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
like image 121
Gunther Struyf Avatar answered Nov 15 '22 05:11

Gunther Struyf


Or without 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 in matlab arrays are addressed by columns

like image 24
yarr Avatar answered Nov 15 '22 05:11

yarr