From: haithem on
Hi, all.

My problem is that I want to generate a sparse vector with a fixed
number of non zero elements randomly distributed.

Thanks for all
From: Bruno Luong on
haithem <haithem.haggui(a)gmail.com> wrote in message <ae397350-a6bc-4935-8d00-3beb656223b0(a)g19g2000yqc.googlegroups.com>...
> Hi, all.
>
> My problem is that I want to generate a sparse vector with a fixed
> number of non zero elements randomly distributed.

A quick and dirty way, this works OK with the density is low. I'm sure there is a better way, but probably requires a lot of code.

m=10;
n=10;
nz=50;

S = sparse([],[],[],m,n);
a = nz - nnz(S);
while a>0
i = ceil(m*rand(1,a));
j = ceil(m*rand(1,a));
S = S + sparse(i,j,1,m,n);
a = nz - nnz(S);
end

Bruno
From: John D'Errico on
"Bruno Luong" <b.luong(a)fogale.findmycountry> wrote in message <hvsbjp$q6u$1(a)fred.mathworks.com>...
> haithem <haithem.haggui(a)gmail.com> wrote in message <ae397350-a6bc-4935-8d00-3beb656223b0(a)g19g2000yqc.googlegroups.com>...
> > Hi, all.
> >
> > My problem is that I want to generate a sparse vector with a fixed
> > number of non zero elements randomly distributed.
>
> A quick and dirty way, this works OK with the density is low. I'm sure there is a better way, but probably requires a lot of code.
>
> m=10;
> n=10;
> nz=50;
>
> S = sparse([],[],[],m,n);
> a = nz - nnz(S);
> while a>0
> i = ceil(m*rand(1,a));
> j = ceil(m*rand(1,a));
> S = S + sparse(i,j,1,m,n);
> a = nz - nnz(S);
> end
>
> Bruno

I would probably use sprand to randomly generate
a sparse matrix with say 10% more zeros on average
than your goal. Then find the non-zeros, and delete
(at random) exactly the number needed to give your
target number of non-zeros.

Other ways exist, but they will take more work than
is worth expending here.

John
From: us on
haithem <haithem.haggui(a)gmail.com> wrote in message <ae397350-a6bc-4935-8d00-3beb656223b0(a)g19g2000yqc.googlegroups.com>...
> Hi, all.
>
> My problem is that I want to generate a sparse vector with a fixed
> number of non zero elements randomly distributed.
>
> Thanks for all

one of the many (other) solutions

n=10;
nr=2;
s=spalloc(1,10,10);
rp=randperm(n);
s(rp(1:nr))=1;

us
From: Bruno Luong on
"us " <us(a)neurol.unizh.ch> wrote in message <hvsnjk$1ju$1(a)fred.mathworks.com>...
> haithem <haithem.haggui(a)gmail.com> wrote in message <ae397350-a6bc-4935-8d00-3beb656223b0(a)g19g2000yqc.googlegroups.com>...
> > Hi, all.
> >
> > My problem is that I want to generate a sparse vector with a fixed
> > number of non zero elements randomly distributed.
> >
> > Thanks for all
>
> one of the many (other) solutions
>
> n=10;
> nr=2;
> s=spalloc(1,10,10);
> rp=randperm(n);
> s(rp(1:nr))=1;
>
> us

The problem is for large sparse matrix size such as m x n = 1e6 x 1e6, generate a randperm of size 1e12 is a no-no.

Bruno