Do loops



"Ben Blomberg" <bblomberg1 at niu.edu> writes:
> I was wondering if there is some function in Maxima that acts like a
> do loop in Mathematica? Something that would like do[eval, {i, imin,
> imax},{j, jmin, jmax}]. In other words it evaluates an expression
> looking over different values of j for each i.
> Or would something like this need to be done in a different way?

If I understand you, you want a nested loop (so eval gets evaluated
(jmax-jmin+1)*(imax-imin+1) times). In Maxima, you just use two loops:

  (%i1) for i : 1 thru 3 do
          for j : 1 thru 3 do
            print ([i,j]);
  [1, 1] 
  [1, 2] 
  [1, 3] 
  [2, 1] 
  [2, 2] 
  [2, 3] 
  [3, 1] 
  [3, 2] 
  [3, 3] 
  (%o1)                                done

Look up "do" in the manual for more examples: you can iterate over lists
as well, rather than having to do it with "for i:1 thru length(list)
..."

Notice that this is a bit like for(...) in C without any curly braces.
Only the following statement gets iterated. If you want several
statements, you can enclose them in brackets like this:

  (%i2) for i : 1 thru 2 do
          for j : 1 thru 2 do
            (print ([i,j]),
             print ([j,i]))$
  [1, 1] 
  [1, 1] 
  [1, 2] 
  [2, 1] 
  [2, 1] 
  [1, 2] 
  [2, 2] 
  [2, 2] 

That said, when writing programs, you often want to bind variables in
the loop body, so you'll often see block used:

  (%i3) for i : 1 thru 2 do
          for j : 1 thru 2 do
            block ([pair: [i,j]],
              print (pair),
              print (reverse (pair)))$
  [1, 1] 
  [1, 1] 
  [1, 2] 
  [2, 1] 
  [2, 1] 
  [1, 2] 
  [2, 2] 
  [2, 2] 

(Yes, this is a very silly example)

Rupert
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 315 bytes
Desc: not available
URL: <http://www.math.utexas.edu/pipermail/maxima/attachments/20130206/8725b16e/attachment.pgp>;