Do I have to declare a list before using it in a loop?
for example:
For[i = 1, i < 10, i++, A[[i]] = i];
The output is:
Symbol A in part assignment does not have an immediate value
What is the proper way to do this?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityDo I have to declare a list before using it in a loop?
for example:
For[i = 1, i < 10, i++, A[[i]] = i];
The output is:
Symbol A in part assignment does not have an immediate value
What is the proper way to do this?
This is quite regular.
a = {};
For[i = 1, i < 10, i++, AppendTo[a, i]]
the result:
a
{1, 2, 3, 4, 5, 6, 7, 8, 9}
Otherwise you could do
a = ConstantArray[Null, 10 - 1];
For[i = 1, i < 10, i++, a[[i]] = i]
or
a = ConstantArray[Null, 10 - 1];
Array[(a[[#]] = #) &, 9]
Or simply using function variables:
Clear[a]
Array[(a[#] = #) &, 9]
but this does not give list a
, although the elements can be referenced, e.g.
a[4]
4
Mathematica is not a declarative language. Don't expect to declare things.
Mathematica is clumsy as a procedural language, so avoid For[]
loops.
Avoid using upper case to start your symbol names to prevent conflicts with the thousands of built-in symbols.
Use a functional programming approach:
a = Table[i, {i, 1, 10}]
Table[i,{i, 10}]
OR
Range @ 10
OR
RandomInteger[100,10]
OR
RandomReal[1,10]
If you just want to generate a list you can use a set of functions such as: Table, Range, RandomInteger, RandomReal etc.
Also see associated tutorial for list generation: Link
A
first if you want your code to work as it is, e.g. like this:A = ConstantArray[Null, 9]
or use. Better though to useTable
orArray
:Array[# &, 9]
. $\endgroup$ – Yves Klett Dec 21 '15 at 18:04