如何在 MATLAB 中使用元胞数组制作稀疏矩阵?
How can do I make a sparse matrix using cell arrays in MATLAB?
稀疏矩阵是一个大矩阵,几乎所有元素都具有相同的值(通常为零)。当可用更少的信息捕获有用信息时,稀疏矩阵的正常表示会占用大量内存。表示稀疏矩阵的一种可能方法是使用元胞向量,其第一个元素是表示稀疏矩阵大小的二元向量。第二个元素是一个标量,指定稀疏矩阵的默认值。元胞向量的每个连续元素都是一个 3 元素向量,表示稀疏矩阵中具有非默认值的一个元素。这三个元素是行索引、列索引和实际值。编写一个名为 sparse2matrix 的函数,它采用上面定义的元胞向量的单个输入和 returns 称为矩阵的输出参数,传统形式的矩阵。
cellvec = {[2 3], 0, [1 2 3], [2 2 -3]};
matrix = sparse2matrix(cellvec)
matrix =
0 3 0
0 -3 0
根据问题中的信息:
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.
所以程序很简单:
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
稀疏矩阵是一个大矩阵,几乎所有元素都具有相同的值(通常为零)。当可用更少的信息捕获有用信息时,稀疏矩阵的正常表示会占用大量内存。表示稀疏矩阵的一种可能方法是使用元胞向量,其第一个元素是表示稀疏矩阵大小的二元向量。第二个元素是一个标量,指定稀疏矩阵的默认值。元胞向量的每个连续元素都是一个 3 元素向量,表示稀疏矩阵中具有非默认值的一个元素。这三个元素是行索引、列索引和实际值。编写一个名为 sparse2matrix 的函数,它采用上面定义的元胞向量的单个输入和 returns 称为矩阵的输出参数,传统形式的矩阵。
cellvec = {[2 3], 0, [1 2 3], [2 2 -3]};
matrix = sparse2matrix(cellvec)
matrix =
0 3 0
0 -3 0
根据问题中的信息:
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]
wherei
,j
is the location in the matrix andx
is the value of the element.
所以程序很简单:
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