How can do I make a sparse matrix using cell arrays in MATLAB?

冷暖自知 提交于 2019-12-13 09:20:47

问题


A sparse matrix is a large matrix with almost all elements of the same value (typically zero). The normal representation of a sparse matrix takes up lots of memory when the useful information can be captured with much less. A possible way to represent a sparse matrix is with a cell vector whose first element is a 2-element vector representing the size of the sparse matrix. The second element is a scalar specifying the default value of the sparse matrix. Each successive element of the cell vector is a 3-element vector representing one element of the sparse matrix that has a value other than the default. The three elements are the row index, the column index and the actual value. Write a function called sparse2matrix that takes a single input of a cell vector as defined above and returns the output argument called matrix, the matrix in its traditional form.

cellvec = {[2 3], 0, [1 2 3], [2 2 -3]};
matrix = sparse2matrix(cellvec)
matrix =
     0     3     0
     0    -3     0

回答1:


A vectorized form of Abdulrhman Aboghanima's answer:

function a = sparse2matrix(cellvec)
a = zeros(cellvec{1}) + cellvec{2};
v = cat(1, cellvec{3:end});
a(sub2ind(cellvec{1}, v(:,1), v(:,2))) = v(:,3);



回答2:


By the information in the question :

In vector cell arrays it is usually the first vector used as a sparse matrix dimension

The second element is a scalar specifying the default value of the sparse matrix

The other vectors are used to specify the location and the value of the element in the sparse matrix , i.e. [i, j, x] where i,j is the location in the matrix and x is the value of the element.

So the program is simply :

function matrix=sparse2matrix(cellvec);

matrix=zeros(cellvec{1})+cellvec{2};

for i=3:length(cellvec)

      matrix(cellvec{i}(1,1),cellvec{i}(1,2))=cellvec{i}(3);

end

Best wishes Abdulrhman Aboghanima



来源:https://stackoverflow.com/questions/56455160/how-can-do-i-make-a-sparse-matrix-using-cell-arrays-in-matlab

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