How to Repeatedly Calculate and Store Values in Mathematica?

  • Context: Mathematica 
  • Thread starter Thread starter Anna Kaladze
  • Start date Start date
  • Tags Tags
    Mathematica
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 3K views
Anna Kaladze
Messages
34
Reaction score
0
Hi,

I have the following simple code in Mathematica:

a=1;
step=0.5;
b=2;
y=a^2-5
-4

What I need to do, is make Mathematica calculate the value of y each time for a different value of "a" ranging from the initial value of 1 to "b"(=2) in "step" increment (=0.5), and remember previous values of y in constructing a final array of y. That is, the answer would be y={-4, -2.75,-1}. It would be great to avoid using Table commands or tampering with the individual lines much. Just plain simple multiple iterations which would “nicely” lead to the y array of 3 numbers.

Any help is appreciated.

Thanks a lot.

Anna.
 
Physics news on Phys.org
I don't see how you can do this without using arrays. So you have...

atable=Table[1+(i-1)*0.5,{i,1,3}];
ytable=Table[Extract[atable,i]^2-5,{i,1,Length[atable]}];
 
Something like the http://reference.wolfram.com/mathematica/guide/ProceduralProgramming.html" construct

Code:
In[1]:= a=1;
        step=0.5;
        b=2;
        y={};
        While[a<=b, AppendTo[y,a^2-5]; a+=step]
        y
Out[6]= {-4,-2.75,-1.}

Of course, this is much slower than using Do or Table (etc) for two reasons;
1) At each step it has to make the comparison a <= b
2) Modifying Lists using AppendTo is a slow way to construct a list. http://reference.wolfram.com/legacy/v5_2/Built-inFunctions/AdvancedDocumentation/LinearAlgebra/LinearAlgebraInMathematica/Performance/ProgrammingEfficiency/AdvancedDocumentationLinearAlgebra5.1.1.html" .

That said, I assume that this is a simple example you constructed and that in your actual code the real bottle neck will lie somewhere else, so the above to considerations can be safely ignored.

The advantage of the above code is that it could easily be put into a
http://reference.wolfram.com/mathematica/ref/Compile.html"
command and be made quite fast.
 
Last edited by a moderator: