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.
Instead of declaring and then filling a sparse matrix, you can fill it at the same time you define it:
It's fairly simple
i'd use
i believe that should fix your problem by treating the matrix as a vector
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 -Get the linear indices to index into K using
sub2ind
and set them -