Working with Symbolic and Numeric Values at the Same Time
- To: mathgroup at smc.vnet.net
- Subject: [mg41637] Working with Symbolic and Numeric Values at the Same Time
- From: "David Park" <djmp at earthlink.net>
- Date: Thu, 29 May 2003 08:14:06 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
Greg,
I'm posting this to MathGroup also because it may be of general interest and
other people might have better suggestions.
If you want to have a symbolic entity and also use it with values, then the
best solution is to use rules to substitute values into the entity. As a
simple example if you have
r:= Sqrt[x^2+y^2]
and you want to do calculations with r, say Solve for y, then don't write
x = 1
y = 2
because then you have to remember to Clear x and y before working
symbolically. Rather write
data = {x -> 1, y -> 2}
Then you can work symbolically with r and x and y all you want. When you
want actual numberical values just substitute the data
expression[involving r, x, y] /. data
and the symbolic expressions are still intact.
For use with your matrix this is a little more difficult.
M = Array[m, {2, 2}];
If you usually want to set all the values at once you could use the
routine...
SetMRules1[valuemat_] := (MRules = Thread[Flatten[M] -> Flatten[valuemat]];)
SetMRules1[{{1, 2}, {3, 4}}]
MRules
{m[1, 1] -> 1, m[1, 2] -> 2, m[2, 1] -> 3, m[2, 2] -> 4}
M is still intact as a symbolic matrix and
M /. MRules
gives the numerical form of the matrix.
If your code requires setting values one at a time you could use the routine
SetMRules2[{i_, j_}, value_] :=
(MRules = MRules /. Rule[m[i, j], _] :> Sequence[];
MRules = Sort[Join[MRules, {m[i, j] -> value}]];)
which will build a list of rules for the matrix elements. Sequence[] gets
rid of an existing element in a list.
MRules = {}
SetMRules2[{1, 1}, 2]
MRules
SetMRules2[{1, 2}, a]
MRules
SetMRules2[{1, 1}, 3]
MRules
giving
{}
{m[1, 1] -> 2}
{m[1, 1] -> 2, m[1, 2] -> a}
{m[1, 1] -> 3, m[1, 2] -> a}
David Park
djmp at earthlink.net
http://home.earthlink.net/~djmp/
From: Gregory Lypny [mailto:gregory.lypny at videotron.ca]
To: mathgroup at smc.vnet.net
On a related note, I was wondering whether it is possible to clear all
numerical values in a matrix in one shot without clearing the
underlying element symbols that were created using Array. Any thoughts?
For example,
M = Array[m{2,2}] displays M={{m[1,1],m[1,2]},{m[2,1],m[2,2]}}
then assign numbers to the elements individually as m[1,2]=7, etc.
... do some calculations using M
Now I'd like to clear M and go back to the original symbolic or
algebraic display; or, if not clear it of values, be able to flip back
and forth between numerical and algebraic displays for exposition.
Regards,
Greg