给定非零元素的位置,如何在MATLAB中创建稀疏矩阵 [英] How to create a sparse matrix in MATLAB given the locations of non-zero elements

查看:77
本文介绍了给定非零元素的位置,如何在MATLAB中创建稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在MATLAB中创建符合以下要求的矩阵.给定向量v,例如[1,2,2,1,3,5,1],我需要形成一个矩阵:

I need to create matrix in MATLAB with the following requirement. Given a vector v, for example, [1,2,2,1,3,5,1], I need to form a matrix:

[1 0 0 1 0 0 1;
 0 1 1 0 0 0 0;
 0 0 0 0 1 0 0;
 0 0 0 0 0 0 0;
 0 0 0 0 0 1 0]

即矩阵的i列在行v[i]处仅包含一个非零元素(单个1).如何避免循环并以有效的方式做到这一点?

i.e. the matrix's ith column contains only one non-zero element (a single 1) at row v[i]. How can I avoid a loop and do this in an efficient way?

推荐答案

其他人指出,这里的循环很好.我会指出,稀疏比FAR更好.您的矩阵非常稀疏,因此请使用稀疏功能解决问题,并在矩阵较大的情况下节省大量存储空间.

Others are pointing out that loops are fine here. I'll point out that sparse is FAR better. Your matrix is sparse, very much so, so use the capability of sparse to solve the problem, and save a vast amount of storage in case that matrix is large.

N = 3000;
v = ceil(rand(1,3000)*3000);

tic
A = zeros(N,N);
for i = 1:N
  A(v(i),i) = 1;
end
toc
Elapsed time is 0.069082 seconds.

tic
B = sparse(v,1:N,1,N,N);
toc
Elapsed time is 0.001308 seconds.

因此,如果矩阵很大,则时间会有很大的差异.

So if the matrix is at all large, there is a huge difference in time.

空间怎么样?

whos A B
  Name         Size                 Bytes  Class     Attributes

  A         3000x3000            72000000  double              
  B         3000x3000               72008  double    sparse    

否则矩阵相同.

sum(sum(abs(A - B)))
ans =
     0

稀疏矩阵占用的空间很小,您可以像使用其他任何矩阵一样使用它.

The sparse matrix takes very little space, and you can use it just like any other matrix.

使用MATLAB的功能.

Use the capabilities of MATLAB.

这篇关于给定非零元素的位置,如何在MATLAB中创建稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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