Reputation: 35
I'm a beginner in Mathematica programming. My code is not running as expected. I wonder if anyone could examine what goes wrong? Here is part of the code.
F[{k_, n_, x_}] =
Which[k == 0, f[a, b, x],
k == 1, g[a, b, n, x],
k == 2, h[c, d, n, x]]
G[x_] = F[{0, 0, x}]
While[Extract[G[x], 1] != 3, G[x_] = F[G[x]]]
The functions f
, g
and h
are defined by Which
as is F
, and they are all vector-valued so that it makes sense to iterate F
. What I want to achieve is: given initial value {0,0,x}
, keep iterating F
until the first component of F
becomes 3
. Is there anything, e.g. syntax, wrong in the above code?
Thanks!
Upvotes: 0
Views: 1093
Reputation: 70763
As jVincent mentioned, I would use :=
instead of =
while defining F.
I would also use the built in NestWhile
instead of manually iterating.
NestWhile[F, {0, 0, x}, Function[e, Extract[e, 1] != 3]]
I can't quite comment on how to correct the code as written because I'm not entirely sure how reassigning G
in the While
works.
Upvotes: 2
Reputation: 556
You need to use SetDelayed
(:=
) for function definitions like: F[x_]:=x
. When you use Set
(=
) like F[x_]=x
, the it is essentially the same as F[_]=x
since the definition isn't delayed until evaluation, so there is no way to transfer the matched pattern on the left hand side into the evaluation of the right hand side.
Upvotes: 3