help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Order of Evaluation


From: Mike Miller
Subject: Re: Order of Evaluation
Date: Mon, 19 Aug 2019 15:17:00 -0700
User-agent: Mutt/1.10.1 (2018-07-13)

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)");

Couldn't you simply define another auxiliary y1 function, for example

    y1 = @(x) f(x) + g(x);
    y = @(x) y1(h(x));

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?

-- 
mike

Attachment: signature.asc
Description: PGP signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]