Search code examples
matlabindices

Matrix indices for creating sparse matrix


I want to create a 4 by 4 sparse matrix A. I want assign values (e.g. 1) to following entries:

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

According to the manual page, I know that I should store the indices by row and column respectively. That is, for row indices,

r=[2,2,2,2,3,3,3,3,4,4,4,4]

Also, for column indices

c=[1,2,3,4,1,2,3,4,1,2,3,4]

Since I want to assign 1 to each of the entries, so I use

value = ones(1,length(r))

Then, my sparse matrix will be

Matrix = sparse(r,c,value,4,4)

My problem is this:

Indeed, I want to construct a square matrix of arbitrary dimension. Says, if it is a 10 by 10 matrix, then my column vector will be

[1,2,..., 10, 1,2, ..., 10, 1,...,10, 1,...10]

For row vector, it will be

[2,2,...,2,3,3,...,3,...,10, 10, ...,10]

I would like to ask if there is a quick way to build these column and row vector in an efficient manner? Thanks in advance.


Solution

  • I think the question aims to create vectors c,r in an easy way.

    n = 4;
    
    c = repmat(1:n,1,n-1);
    r = reshape(repmat(2:n,n,1),1,[]);
    
    Matrix = sparse(r,c,value,n,n);
    

    This will create your specified vectors in general.

    However as pointed out by others full sparse matrixes are not very efficient due to overhead. If I recall correctly a sparse matrix offers advantages if the density is lower than 25%. Having everything except the first row will result in slower performance.