MATLAB How to fill individual entries of a sparse matrix using vectorised form?

╄→гoц情女王★ 提交于 2019-12-13 00:14:54

问题


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)


来源:https://stackoverflow.com/questions/22946354/matlab-how-to-fill-individual-entries-of-a-sparse-matrix-using-vectorised-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!