Re: random matrix initialisation...
- To: mathgroup at smc.vnet.net
- Subject: [mg37616] Re: [mg37576] random matrix initialisation...
- From: Sseziwa Mukasa <mukasa at jeol.com>
- Date: Wed, 6 Nov 2002 06:56:29 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
On Tuesday, November 5, 2002, at 05:01 AM, Manuel Marques-Pita wrote: > > hello, > > i have a question regarding matrices. searched on the web and forums > but maybe due to using wrong keywords i am not finding an answer... > > i need a way or function X to initialise matrices in mathematica such > that each time i call X i get a matrix with a predetermined number of > elements initialised as "1" and the rest as "0" > > examples > > X(4,3) > > {{0,0,0,0}, {0,0,1,0}, {0,0,0,1}, {1,0,0,0}} > > again X(4,3) > > {{1,1,0,0}, {0,0,0,0}, {0,0,0,0}, {0,1,0,0}} > > etc.. (first argument means that the matrix is 4x4 and second means > that there should be 3 "1's" present in the matrix > > any help, pointers, etc will be appreciated! > How about: << DiscreteMath`Combinatorica` generateRow[m_,n_,1]:=With[{p=RandomKSubset[m,n]},{Table[If[MemberQ[p,i] ,1,0],{i,m}]}] generateRow[m_,n_,r_]:=Block[{t=Random[Integer,{0,n}],p},p=RandomKSubset [m,t];{Table[If[MemberQ[p,i],1,0],{i,m}],Sequence@@generateRow[m,n-t,r- 1]}] generateRow[m_,n_]:=generateRow[m,n,m] This should work for small matrices. I suppose you could remove the recursion by using a Do loop which would allow you to create larger matrices without worrying about $RecursionLimit. Regards, Sseziwa