如何使用MATLAB中的单元格数组制作稀疏矩阵? [英] How can do I make a sparse matrix using cell arrays in MATLAB?

查看:232
本文介绍了如何使用MATLAB中的单元格数组制作稀疏矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

稀疏矩阵是一个大型矩阵,几乎所有元素的值都相同(通常为零).当有用信息可以少得多地捕获时,稀疏矩阵的常规表示将占用大量内存.表示稀疏矩阵的一种可能方法是使用单元格向量,该向量的第一个元素是2个元素的向量,表示稀疏矩阵的大小.第二个元素是标量,指定稀疏矩阵的默认值.像元向量的每个连续元素是一个3元素向量,代表稀疏矩阵的一个元素,其值不是默认值.这三个元素是行索引,列索引和实际值.编写一个名为sparse2matrix的函数,该函数接受如上定义的单元格向量的单个输入,并返回称为矩阵的输出参数,该矩阵为传统形式.

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

推荐答案

Abdulrhman Aboghanima的答案的矢量化形式:

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);

这篇关于如何使用MATLAB中的单元格数组制作稀疏矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆