MATLAB-创建伪随机稀疏矩阵 [英] MATLAB - Create psudorandom sparse matrix
本文介绍了MATLAB-创建伪随机稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简单的方法来制作带有特定数量的非零条目的随机"稀疏矩阵?
Is there an easy way of making a 'random' sparse matrix with a specific number of nonzero entries?
这是我的尝试:
r = randperm(n,m) % n = size of matrix, m = number of nonzeros in each column
H = sparse(r, r,1,n,n);
但是矩阵H在每一列中没有正好有m个非零.例如,如果我用它制作一个100 x 100的矩阵,每列中有10个非零,那么只有10列中有10个正1.
But the matrix H doesn't have exactly m nonzeros in each column. For example if I use this to make a 100 x 100 matrix with 10 nonzeros in each column only 10 columns have exactly 10 1's in them.
我敢肯定有一种简单的方法可以做到这一点,但我看不到.
I'm sure there's an easy way to do this but I can't see it.
推荐答案
这将生成一个 100×100
矩阵,每列正好有十个 1
s:
This will generate a 100-by-100
matrix with exactly ten 1
s per column:
n = 100;
m = 10;
nonzerosPerColumn = repmat(m, 1, n);
%%// Build vector of linear indices to nonzero entries
pos = cell2mat(arrayfun(@(i)randperm(n,nonzerosPerColumn(i))+(i-1)*n,1:n,'uni',0));
%%// Generate the matrix
M = reshape(sparse(pos,1,1,n*n,1),n,n);
这篇关于MATLAB-创建伪随机稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文