RE: Initialize a matrix in mathematica
- To: mathgroup at smc.vnet.net
- Subject: [mg66764] RE: [mg66742] Initialize a matrix in mathematica
- From: "David Park" <djmp at earthlink.net>
- Date: Mon, 29 May 2006 06:06:19 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
It looks to me that you are creating a vector and not a matrix. The following routine will create a vector with the name avec and fill it with the values. createavec[ndiv_Integer?Positive] := (avec = Table[i^2, {i, ndiv}];) createavec[5] avec {1, 4, 9, 16, 25} Here is a more general routine that allows you to specify the symbol name for the vector, the size of the vector and the function that will be used to fill the elements. Clear[createavec]; createavec[name_Symbol, size_Integer?Positive, function_Function] := (name = Table[function[i], {i, 1, size}]; createavec[vec, 3, Sin[#]^2 &] vec {Sin[1]^2, Sin[2]^2, Sin[3]^2} Using functional programming such as Table and pure functions (Look up Function in Help) is much better than For loops. Throw For loops into the ash can and never think of them again. David Park djmp at earthlink.net http://home.earthlink.net/~djmp/ From: ashesh [mailto:ashesh.cb at gmail.com] To: mathgroup at smc.vnet.net Hi All, Have programmed in another system until now and am trying to shift to Mathematica and facing some diffciulties 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; Hope some one can help me in doing the above operation Regs.