How to create a sparse matrix with such specifications?

1 回表示 (過去 30 日間)
Shweta
Shweta 2013 年 8 月 9 日
I have to create a sparse matrix whose support is chosen uniformly at random and whose non-zero entries are independent and uniformly distributed in the range [-50,50].
Please help me out...

回答 (1 件)

Richard Brown
Richard Brown 2013 年 8 月 9 日
編集済み: Richard Brown 2013 年 8 月 11 日
edit This version is wrong, but leaving so comment below makes sense
density = 0.01; % For example
m = 10000; n = 10000;
100 * sprand(m, n, density) - 50;
edit This one is better! Basically the same as what James wrote
density = 0.01;
m = 10000; n = 10000;
A = sprand(m, n, density);
A = 100*A - 50*spones(A);
  2 件のコメント
James Tursa
James Tursa 2013 年 8 月 9 日
編集済み: James Tursa 2013 年 8 月 9 日
The -50 will get applied to all elements, not just the non-zero elements. I think you need something like this instead:
s = sprand(m, n, density);
s = 100 * s - 50 * logical(s);
Or maybe use spfun. E.g.,
s = sprand(m, n, density);
f = @(x)(100*x-50);
s = spfun(f,s);
Richard Brown
Richard Brown 2013 年 8 月 11 日
haha, yes, good point! I'm too used to working in C and just looping through the nonzeros. Edited answer accordingly :)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by