0
votes

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.

2
It is impossible to answer this without knowing where exactly you want your nonzero elements. Your example vectors are not at all clear.excaza
Sorry for being unclear. Those nonzero elements are all 1s.nam
It looks like you want to create a dense ones matrix and store it as sparse. Why?TroyHaskin
Where your nonzero elements are, not what your nonzero elements are. You are asking us for a relationship between your row and column indices, this could be basically anything.excaza

2 Answers

3
votes

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.

0
votes

You can sparse a matrix after creating its full version.

A = (10,10);
A(1,:) = 0;
B = sparse(A);