MathGroup Archive 2002

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: random matrix initialisation...

  • To: mathgroup at smc.vnet.net
  • Subject: [mg37631] Re: random matrix initialisation...
  • From: atelesforos at hotmail.com (Orestis Vantzos)
  • Date: Wed, 6 Nov 2002 06:59:08 -0500 (EST)
  • References: <aq86gt$e4j$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Manuel Marques-Pita <manuxu at mac.com> wrote in message news:<aq86gt$e4j$1 at smc.vnet.net>...
> 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!
> 
> thanks a lot
> 
> m
> 
> --

You can use this, where dim is the dimension of the matrix and n the
number of ones that you want:

randMatrix[dim_, n_] := Module[{A, ones = 0, i, j},
    A[__] = 0;
    While[ones < n,
      {i, j} = Table[Random[Integer, {1, dim}], {2}];
      If[A[i, j] == 0, A[i, j] = 1; ones++]];
    Array[A, {dim, dim}]]

Orestis Vantzos


  • Prev by Date: Re: Re: Mathematica on the web
  • Next by Date: Re: How to get the linear independent subset of a list? (Newbie Question)
  • Previous by thread: Re: random matrix initialisation...
  • Next by thread: RE: random matrix initialisation...