Re: Simple Concept I can't figure out! Making rules?
- To: mathgroup at smc.vnet.net
- Subject: [mg38091] Re: [mg38046] Simple Concept I can't figure out! Making rules?
- From: Tomas Garza <tgarza01 at prodigy.net.mx>
- Date: Tue, 3 Dec 2002 04:30:00 -0500 (EST)
- References: <200211281907.OAA23937@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Yes, sometimes guys in engineering faculties have odd fixations. But I think you're quite right in sticking to Mathematica. Anyway, the result of a Solve statement is a list of rules, each of them saying something like "a solution is -> something". In your case, there is only one solution, so the list has only one element, and the solution is the first (and only) element of the list. So, if you write In[1]:= a = N[Solve[2*x - 1 == 0, x]] Out[1]= {{x->0.5}} then the first element of a is In[9]:= a[[1]] Out[9]= {x->0.5} Now you want to use this particular value of x. There are several ways to go about it. One, and perhaps the more instructive, is to look at the FullForm of a[[1]]: In[2]:= FullForm[{x->0.5}] Out[2]//FullForm= List[Rule[x,0.5]] which again says that you're dealing with a list. The first (and only) element of this list is a rule, and the second part of this rule is the numerical value you're looking for: In[3]:= a[[1,1,2]] Out[3]= 0.5 Another way of getting at it is using a ReplaceAll statement. If you write In[4]:= x /. {x -> 0.5} this can be read as "x, where x takes the value 0.5", which, when executed, will yield 0.5. Then you may write directly In[5]:= N[Solve[2*x - 1 == 0, x]][[1,1,2]] Out[5]= 0.5 This is valid in general. If your equation has several solutions, then the first index will lead you to the one you wish to use. Suppose you wanted to use this solution as input to some other problem, e.g., to be used as the argument of a function, like, say Sin[x]. Then you may write In[6]:= Sin[x]/.a[[1]] Out[6]= 0.479426 or In[7]:= Sin[x/.a[[1]]] Out[7]= 0.479426 i.e. you may use the rule on the argument or on the function itself (in this simple example). Tomas Garza Mexico City ----- Original Message ----- From: "Stan" <snarten at runbox.com> To: mathgroup at smc.vnet.net Subject: [mg38091] [mg38046] Simple Concept I can't figure out! Making rules? > Even though it's frowned upon by the engineering college, i use > mathematica a lot of the stuff that would take pages of code in > another system. I have most basic functions and operations down, but I am > lacking one basic thing I need to do to be able to program more > problems successfully: > > here is my problem: > > Lets say you solve an equation using "Solve" > > Solve[2x - 1 == 0, x] // N > > {{x -> 0.5}} > > How would I then use the result of "Solve" (0.5) and assign it to a > new variable, like "answer" for further calculations? > > I think it has something to do with /. and -> rules of some sort, but > I can't get this simple concept to work! > > Thanks for the help. > > -Stan > >