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 4×4 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.

Leave a Comment