Re: Initialize a matrix in mathematica

*To*: mathgroup at smc.vnet.net*Subject*: [mg66755] Re: Initialize a matrix in mathematica*From*: albert <awnl at arcor.de>*Date*: Mon, 29 May 2006 06:05:33 -0400 (EDT)*References*: <e5bt2l$ba3$1@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

Hi, > I would like to create a matrix, say a[ndiv] and would like to > initilize all the value to i^2 (or any other value). The size of the > matrix is not fixed. > > The code I tried to use is: > > ndiv = 5; > a = {}; > For[i=1, i<=ndiv, i++, > a[[i]] = i*i; > ]; > a > > This is producing the following error: > partw: Part 1 of {} does not exist and so on. > > I understand that I am not creating a matrix of size 1*ndiv for the > data to be fed it. > > So I tried using Table as follows: > > a = Table[0,{1},{ndiv}] followed by the above For loop (when I wanted > to initialize the matrix with say i*i; you are close. Keep in mind that a For-loop hardly ever is a good approach in Mathematica (and many other modern languages, too). Why not let Table do all the work? The following is short, easy to read, avoids errors with indexing and even is reasonably fast: a = Table[i^2,{i,1,ndiv}] the following is even shorter and avoids indexing altogether, but might be harder to understand when not used to mathematica: a = Range[ndiv]^2 compared to other systems/languages it might help if you try to tell mathematica what you want to be done instead of telling it how to do it (of course that will only work to some extent). hth, albert PS: If for whatever reason you insist on the extra level of lists try: a = Table[{i^2},{i,1,ndiv}] or: a = List/@Range[ndiv]^2