help-octave
[Top][All Lists]

## Re: Order of Evaluation

 From: fi Subject: Re: Order of Evaluation Date: Tue, 20 Aug 2019 11:27:37 +0200 User-agent: Mutt/1.5.24 (2015-08-30)

```On Mon, Aug 19, 2019 at 03:17:00PM -0700, Mike Miller wrote:
> On Mon, Aug 19, 2019 at 20:56:00 +0200, address@hidden wrote:
> > Dear List,
> >
> > consider the following functions (assumed free of side effects). The
> > functions themself do not matter. Here are some simple examples for
> > clearness:
> >
> >
> > f = @(x) x .^ pi + log(x);   % ... some expression ...
> > g = @(x) sin(x) * exp(-x/5); % ... another expression ...
> > h = @(x) sqrt(x .^ cos(x));  % ... normally a costly (in time) expression
> > ...
> >
> > % and last:
> >
> > y = @(x) f(h(x)) + g(h(x));
> >
> > % here h(x) will be evaluated twice. This is inefficient, especially
> > % if y() is evaluated frequently (e.g. in finding roots or
> > % integrating).
> > %
> > % Unfortunately Octave (like Matlab) does not have a sequence operator like
> > C.
> > % So constructs like the following lead to syntax errors:
> >
> > y = @(x) H = h(x), f(H) + g(H); % also wrong if in brackets
> >
> > % The only idea I found was:
> >
> > y = @(x) f(H = h(x)) + g(H);
>
> You could try using eval or evalin to evaluate a compound expression
> inside an anonymous function, for example
>
>     y = @(x) evalin ("caller", "H = h(x); f(H) + g(H)");

that is an interesting application of the somewhat exotiv
"evalin()". But I am afraid, that the evaluation could have a
performance impact. My goal was to increase the performance as much as
possible.

> Couldn't you simply define another auxiliary y1 function, for example
>
>     y1 = @(x) f(x) + g(x);
>     y = @(x) y1(h(x));

This trick is great and it is robust even if the order of evaluation
is not guaranteed.

> Lastly, you could define y as a true function rather than an anonymous
> function
>
>     function res = y(x); H = h(x); res = f(H) + g(H); endfunction
>
> Is there a reason to constrain yourself to use only anonymous functions?

I have noticed, that anonymous functions are handled faster than true
functions (but maybe this is wrong for recent versions of Octave). My
expressions are basically simple and my goal was maximum performance
(because evaluation takes place frequently).

best regards

Torsten Finke

--
------------------------------------------------------------------------
Dr.-Ing. Torsten Finke