Message Boards Message Boards

1
|
3649 Views
|
1 Reply
|
2 Total Likes
View groups...
Share
Share this post:
GROUPS:

Create a function and plot the graph

Posted 11 years ago
Hello,
I just startted with Mathematica and I got a problem.
It seems I don't understand the syntax of functions.
Please, what is the problem in this source? 
Thanks!
 DDpPl := sk*Log[r3/r1]
 DDpEl := sk/2 * (r2^2 - r3^3)/(r3^2*r2^2)
 DDp := DDpEl + DDpPl
 DDp /. {r1 -> 0.2, r2 -> 0.3, r3 -> 0.25,sk -> 300*10^6}(* test -- OK *)
 Plot[DDp, {r3, r1, r2}] /. {r1 -> 0.2, r2 -> 0.3,sk -> 300*10^6} (* No graph - why? *)
 
 DD[r3_] := Evaluate[DDp](*try another way*)
 DD[0.25](* test -- OK *)
 DD[0.25] /. {r1 -> 0.2, r2 -> 0.3, sk -> 300*10^6} (* test -- OK *)
Plot[DD[r3], {r3, r1, r2}] /. {r1 -> 0.2, r2 -> 0.3,sk -> 300*10^6}(* No graph - why? *)
POSTED BY: Tomáš Hruš
The issue is order of evaluation. When using Replace (/.) the left hand side is evaluated and then the replacement happens. It happens in that order. Your code does not work because it would require the substitution to happen before the evaluation.

Plot requires you to give it a function that it can plot and a domain over which to plot before it can be evaluated.

When values such as DDp depend on the values of some other symbols, it really is often best to define functions. It helps keep track of what each function depends on and has a number of really positive benefits when trying to write organized and testable code.
Clear[DDpP1, DDpE1, DDp]

DDpPl[r1_, r2_, r3_, sk_] := sk*Log[r3/r1]
DDpEl[r1_, r2_, r3_, sk_] := sk/2*(r2^2 - r3^3)/(r3^2*r2^2)
DDp[r1_, r2_, r3_, sk_] := DDpEl[r1, r2, r3, sk] + DDpPl[r1, r2, r3, sk]
You can use a With statement if you like when Plotting:
With[{r1 = 0.2, r2 = 0.3, sk = 300*10^6},
     Plot[DDp[r1, r2, r3, sk], {r3, r1, r2}]
]

POSTED BY: Sean Clarke
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract