0
$\begingroup$

I have the following code:

f = 6;
t0 = 0.0;
t1 = 50.0;
m[t_] := {Cos[2 Pi*f*t], 0.0, 0.0};
Plot[Part[m[t], 1], {t, t0, t1}, Frame -> True,
FrameLabel -> {Style["Time", FontSize -> 16], 
Style["Amplitude", FontSize -> 16]},
PlotRange -> All, PlotStyle -> {Red}]

The result is:

enter image description here

I want to rewrite the code using OptionsPattern as follows:

gt0 = 0.0;
gt1 = 50;
gf = 6;

ClearAll[af];
Options[af] = {
T0 -> gt0,
T1 -> gt1,
Frequency -> gf,
};

af[
OptionsPattern[]
] := Module[
{
t0 = OptionValue[T0],
t1 = OptionValue[T1],
f = OptionValue[Frequency],
m, t
},
m = {Cos[2 Pi*f*t], 0.0, 0.0}
]

rmt = af[];

Plot[Part[rmt[t], 1], {t, gt0, gt1}, Frame -> True,
FrameLabel -> {Style["Time", FontSize -> 16], 
Style["Amplitude", FontSize -> 16]}, PlotRange -> All,
PlotStyle -> {Red}]

The result is:

enter image description here

Why are these two plots not the same?

$\endgroup$

2 Answers 2

3
$\begingroup$

Your 2nd code example is wrong. It should be

gt0 = 0.0;
gt1 = 1.0; (* I am changing this to get a more reasonable plot *)
gf = 6; 

ClearAll[af];
Options[af] = {Frequency -> gf}; (* you don't use any other options *)
af[OptionsPattern[]] := {Cos[2 Pi*OptionValue[Frequency]*t], 0.0, 0.0}
rmt = af[]

Plot[Part[rmt, 1], {t, gt0, gt1}, 
  Frame -> True, 
  FrameLabel -> {Style["Time", FontSize -> 16], Style["Amplitude", FontSize -> 16]},
  PlotRange -> All, 
  PlotStyle -> {Red}]

plot

$\endgroup$
3
$\begingroup$

Let's see what rmt looks like:

rmt

{Cos[12 π t$34324], 0., 0.}

Notice that the t variable is actually a module variable! Next, let's consider rmt[t]:

rmt[t]

{Cos[12 π t$34324], 0., 0.}[t]

Finally, what does Part[rmt[t], 1] look like:

Part[rmt[t], 1]

t

So, your second example ends up plotting just t, and not Cos[12 Pi t]. This is why they are different.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.