Creating Indicator Matrix

The thing about an indicator matrix like this, is it is better if you make it sparse. You will almost always be doing a matrix multiply with it anyway, so make that multiply an efficient one.

n = 4;
V = [3;2;1;4];
M = sparse(V,1:n,1,n,n);
M =
   (3,1)        1
   (2,2)        1
   (1,3)        1
   (4,4)        1

If you insist on M being a full matrix, then making it so is simple after the fact, by use of full.

full(M)
ans =
     0     0     1     0
     0     1     0     0
     1     0     0     0
     0     0     0     1

Learn how to use sparse matrices. You will gain greatly from doing so. Admittedly, for a 4x4 matrix, sparse will not gain by much. But the example cases are never your true problem. Suppose that n was really 2000?

n = 2000;
V = randperm(n);
M = sparse(V,1:n,1,n,n);
FM = full(M);

whos FM M
  Name         Size                 Bytes  Class     Attributes

  FM        2000x2000            32000000  double              
  M         2000x2000               48008  double    sparse    

Sparse matrices do not gain only in terms of memory used. Compare the time required for a single matrix multiply.

A = magic(2000);

tic,B = A*M;toc
Elapsed time is 0.012803 seconds.

tic,B = A*FM;toc
Elapsed time is 0.560671 seconds.

a quick way to do this - if you do not require sparse matrix - is to create an identity matrix, of size at least the max(v), then to create your indicator matrix by extracting indexes from v:

m = max(V);
I = eye(m);
V = I(V, :);

You would like to create the Index matrix to be sparse for memory sake. It is as easy as:

vSize = size(V);
Index = sparse(vSize(1),max(V));
for i = 1:vSize(1)
    Index(i, v(i)) = 1;
end

I've used this myself, enjoy :)


You can simply combine the column index in V with a row index to create a linear index, then use that to fill M (initialized to zeroes):

M = zeros(numel(V), max(V));
M((1:numel(V))+(V.'-1).*numel(V)) = 1;