Search code examples
matlabsparse-matrix

sparse matrix parallel to the full matrix syntax of A(ind,ind)=1 in Matlab


In Matlab I can populate all combinations of elements in a full matrix by doing the following:

A=zeros(5);
ind=[1 4 5];
A(ind,ind)=1

 A =
     1     0     0     1     1
     0     0     0     0     0
     0     0     0     0     0
     1     0     0     1     1
     1     0     0     1     1

How can I accomplish that when my matrix A is sparse? (say A=zeros(1e6) and I only want ~1000 elements to be 1 etc...)


Solution

  • You can use the sparse command, as follows:

    % create a 5x5 sparse matrix A, with 1's at A(ind,ind)
    [row,col] = meshgrid(ind,ind); % form indexing combinations
    row = row(:); % rearrange matrices to column vectors
    col = col(:);
    A = sparse(row, col, 1, 5, 5);
    

    While it is possible to index sparse matrices using the conventional A(1,2) = 1 style, generally this is not a good idea. MATLAB sparse matrices are stored very differently to full matrices behind the scenes and do not support efficient dynamic indexing of this kind.

    To get good performance sparse matrices should be built in one go using the sparse(i,j,x,m,n) syntax.