Group Abstract Group Abstract

Message Boards Message Boards

0
|
3.2K Views
|
2 Replies
|
1 Total Like
View groups...
Share
Share this post:

[?] Declare the size of a List variable?

Posted 8 years ago

Hello, I am new to Mathematica and trying to understand how to use it so I hope you will excuse me if this question is too elementary.

After looking at some tutorials and read the book “An elementary introduction to Wolfram Language” I have seen a large number of examples how to “manually” fill a List (vector) with values (for example: List[a, b, c, d], Table[x, 10] and so on).

However, when I try to enter the results from a calculation into a List variable I run into problems. It seems that the List variable must have been declared (initiated?) in one way or the other before it works.

In the small example attached I have “initiated” my List variable (vector1) with “null” and then I can run the For-loop. In the example below I did not “initiate” the List variable (vector2) and I receive an error message.

How do I do if I don’t know in advance how many elements my variable will contain?

/CKY

Attachments:
POSTED BY: cky
2 Replies

Like pretty much all programming languages, you can't assign values to elements outside the length of a list. There are multiple ways in Mathematica:

  • Start with an empty list x ={}, then use Append (or AppendTo) to make it bigger each time.
  • Use Sow & Reap construct, this will take care of enlarging
  • Use Table; this will then create the list for you
  • …
POSTED BY: Sander Huisman
Posted 8 years ago

Thank you for the answer. That solves one of my many questions.

POSTED BY: cky
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard