MATLAB How to fill individual entries of a sparse

2019-08-10 12:25发布

问题:

I have a sparse matrix and I need to fill certain entries with a specific value, I am using a for loop right now but I know its not the correct way to do it so I was wondering if its possible to vectorise this for loop?

K = sparse(N);
for i=vectorofrandomintegers
    K(i,i) = 1;
end

If I vectorise it normally as so:

K(A,A) = 1;

then it fills all the entries in each row denoted by A whereas I want individual entries (i.e. K(1,1) = 1 or K(6,6)=1).

Also, the entries are not diagonally adjacent so I can't plop the identity matrix into it.

回答1:

If you are going to use a vectorized method, you would need to get the linear indices to be set. The issue is that if you define your sparse matrix as K = sparse(N) and then linearly index into K, it would extend the size of it in one direction only and not along both row and column. Thus, you need to specify to MATLAB that you are looking to use this sparse to store a 2D array. Thus, it would be -

K = sparse(N,N);

Get the linear indices to index into K using sub2ind and set them -

ind1 = sub2ind([N N],vectorofrandomintegers,vectorofrandomintegers);
K(ind1) = 1;


回答2:

It's fairly simple

i'd use

K((A-1)*N+A))=1;

i believe that should fix your problem by treating the matrix as a vector



回答3:

Instead of declaring and then filling a sparse matrix, you can fill it at the same time you define it:

i = vectorofrandomintegers; j = i;
K = sparse(i,j,1,N,N)