【问题标题】:MATLAB - Create psudorandom sparse matrixMATLAB - 创建伪随机稀疏矩阵
【发布时间】:2015-02-12 19:56:13
【问题描述】:

是否有一种简单的方法可以制作具有特定数量的非零条目的“随机”稀疏矩阵?

这是我的尝试:

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。

我确信有一种简单的方法可以做到这一点,但我看不到。

【问题讨论】:

  • 您想要每列中的特定数量的非零,还是整个矩阵中特定数量的非零就足够了?顺便说一句:我怀疑你的尝试会产生一个每列有多个条目的矩阵,因为它只会在对角线上的随机位置生成1s。
  • @knedlsepp 理想情况下,矩阵在每列中都有特定数量的非零。矩阵 H = randweb(100,10) 有 955 个非零值,我想附上 spy 图,但我的代表不够高。

标签: matlab matrix


【解决方案1】:

这将生成一个100-by-100 矩阵,每列正好有十个1s:

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

【讨论】:

    【解决方案2】:

    这是一种矢量化方法:

    r = 100;  %// number of rows
    c = 100;  %// number of columns
    m = 10;   %// number of ones that there should be in each column
    H = sparse([], [], [], r, c, c*m);     %// preallocate and initiallize to zero
    [~, ind] = sort(rand(r,c));            %// randomly generate...
    ind = ind(1:m,:);                      %// ... m row indices per column
    H(bsxfun(@plus, ind, (0:c-1)*r)) = 1;  %// fill in ones, using linear indexing
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-14
      • 2012-01-10
      • 2013-04-11
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      相关资源
      最近更新 更多