I would like some advice about the use of memoization in conjunction with conditional statements. Let me try to explain my problem:
I am constructing a function depending on a number of parameters. Given a set of values I first need to check if they meet certain conditions and then calculate the value of the function like so:
myfunction[V_,a_,b_,c_]:=Block[
{v1},
If[TrueQ[a<b]&&TrueQ[b>c],Abort[]];
a*V^2+b*V+c
]
The reason why I am constructing the function this way is because I need to study the variation of myfunction
with V
for different values of the parameters a
, b
and c
and eventually plot some dependencies. So what I would like to have is to stop the evaluation of the function if the set of parameters a
, b
and c
does not meet the conditions and if they do to plot the variation with V
(this case is the easy part).
In its current form myfunction
evaluates without a problem, but is quite slow. Having the If
evaluated for every value of V
when plotting the function, is very time consuming, considering that it only needs to be evaluated once.
So I thought I found the solution when I read about memoization. I have tried to rewrite the function like this:
myfunction[V_,a_,b_,c_]:=Block[
{v1,memo},
memo:=memo=If[TrueQ[a<b]&&TrueQ[b>c],Abort[],0.];
a*V^2+b*V+c
]
But it is not working. The Abort[]
is never evaluated, only when TrueQ
is False
memo becomes 0 and that's all.
Is there a way to accomplish this?
Let me know if you need more details.
Update:
Thank you very much for your comments. Following ybeltukov's suggestion I have tried the following:
created a function
ExistCond[a_,b_,c_]=Block[
{some parameters},
definitions;
TrueQ[a<b]&&TrueQ[b>c](*main conditions to be satisfied*)
];
then use it as follows with myfunction
:
myfunction[V_,a_,b_,c_]/;ExistCond[a,b,c]:=myfunction[V,a,b,c]=Block[
{extra parameters},
definitions;
a*V^2+b*V+c
];
Unfortunately when I plot myfunction
it takes a long time first time I evaluate the plot and alas, the second time is very fast. But this is not what I intended. I was expecting that If the conditions in ExistCond
evaluate to True
then for the rest of the values of V
, ExistCond
is not evaluated again. I have a feeling I am confusing how memoization works.
myfunction[V_, a_, b_, c_] /; a < b && b > c := myfunction[V, a, b, c] = a*V^2 + b*V + c;
? $\endgroup$/;
is more convenient for conditions. For example, see my recent answer with conditions and memoization . $\endgroup$mem : myfunction[V_, a_, b_, c_] /; a < b && b > c := mem = a*V^2 + b*V + c;
$\endgroup$V
. For testing purpose you might want to use a fuction like(Pause[10];a V^2+b V+c)
$\endgroup$ExistCond[]
instead $\endgroup$