MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

RE: If-statement problems

  • To: mathgroup at
  • Subject: [mg49493] RE: [mg49472] If-statement problems
  • From: "David Park" <djmp at>
  • Date: Thu, 22 Jul 2004 02:45:01 -0400 (EDT)
  • Sender: owner-wri-mathgroup at


Forget For statements. Mathematica has much more natural ways for doing

You could just use a simple Set statement as follows:

{a, b, c, d} = {5, 6, 7, 8};

{a, b, c, d}
{5, 6, 7, 8}

Then an expression involving these variables is automatically evaluated.

a^2b/(c(1 - d))

But then you can't use a,b,c and d as symbols anymore. I usually try not to
set values for single variable symbols. Setting them and then later
forgetting that they have values is one of the most common errors in
Mathematica. Another method is to set rules for them.

Clear[a, b, c, d]
valuerules = Thread[{a, b, c, d} -> {5, 6, 7, 8}]
{a -> 5, b -> 6, c -> 7, d -> 8}

You can then substitute into an expression involving these variables using
the rules, without destroying the ability to use the variables as symbols.

a^2b/(c(1 - d))
% /. valuerules
(a^2*b)/(c*(1 - d))

Which method is best depends on your own convenience.

As for the For and If (with a capital I) statements I'll let others explain
them because they are far too complicated for me.

David Park
djmp at

From: Aaron Fude [mailto:aaronfude at]
To: mathgroup at


New to Mathematica. I can't figure out how to use the if-statement for pure
flow control.

Here's an example:

A = {5, 6, 7, 8}
For [n = 1, n <= 4, n++,
 if [n == 1, a = A[[n]]];
 if [n == 2, b = A[[n]]];
 if [n == 3, c = A[[n]]];
 if [n == 4, d = A[[n]]];

I want to assign to a b c and d the 4 values from A. Obviously, that's not
what happens. How do I accomplish what I need?

Many thanks in advance!!!

Aaron Fude

  • Prev by Date: RE: simple problem with Map?!?
  • Next by Date: Re: Plotting a function and its derivative
  • Previous by thread: Re: If-statement problems
  • Next by thread: Re: If-statement problems