4
$\begingroup$

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?

$\endgroup$
2
  • 2
    $\begingroup$ You need to initialize 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 use Table or Array: Array[# &, 9]. $\endgroup$ – Yves Klett Dec 21 '15 at 18:04
  • 1
    $\begingroup$ @jarhead, that is a useful article $\endgroup$ – garej Dec 21 '15 at 19:42
4
$\begingroup$

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

$\endgroup$
5
$\begingroup$

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}]
$\endgroup$
5
$\begingroup$
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

$\endgroup$
4
  • $\begingroup$ You missed the point, the calculation for A[[i]] is just an example....I have there a more complicated calculation $\endgroup$ – jarhead Dec 22 '15 at 12:06
  • $\begingroup$ @jarhead I do apologise. $\endgroup$ – e.doroskevic Dec 22 '15 at 12:11
  • $\begingroup$ but thanks for the info though $\endgroup$ – jarhead Dec 22 '15 at 12:15
  • $\begingroup$ @jarhead glad you found it useful! $\endgroup$ – e.doroskevic Dec 22 '15 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.