Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: objects containing functions
Date: Tue, 30 Mar 2010 09:18:02 +0000 (UTC)
Organization: University of Nottingham
Lines: 39
Message-ID: <hosfka$gv8$1@fred.mathworks.com>
References: <hoqo8l$4vl$1@fred.mathworks.com> <hoqpdm$nq9$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1269940682 17384 172.30.248.37 (30 Mar 2010 09:18:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 30 Mar 2010 09:18:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1072079
Xref: news.mathworks.com comp.soft-sys.matlab:621771

"Steven Lord" <slord@mathworks.com> wrote in message <hoqpdm$nq9$1@fred.mathworks.com>...
> 
> "Simon Preston" <preston.simon+mathsworks@gmail.com> wrote in message 
> news:hoqo8l$4vl$1@fred.mathworks.com...

> > Any suggestions how I could do this better - i.e. ways of defining f 
> > within the object, but so it is as fast to evaluate as if it were a 
> > separate function?
> 
> Use a function handle.

Steve and Rob, thanks for your replies.

By inline, I mean using the function "inline" which I think stores the function as a string and uses "eval" whenever called, hence being slow.

Steve's suggestion to use function handles gives a big improvement over inline.  However, for my function f to be contained within the object, (I think) I need to use an anonymous function - I have tried this, and it runs slower by a factor of 2 compared with calling a function defined in the standard way.  Why is this and can it be avoided?

Running the below code repeatedly shows the issue.

Thanks for your help, S



function [] = test_anon_function_speed()

fn_anon = @(t,x,theta)[-theta(1)*x(1)+theta(1)*x(2);theta(2)*x(1)-x(2)-x(1)*x(3);-theta(3)*x(3)+x(1)*x(2)];

theta = rand(3,1);
x = rand(3,1);

tic;fn([],x,theta);toc;

tic;fn_anon([],x,theta);toc;

% ---------------------------------------------------------------------

function out = fn(t,x,theta)

out = [-theta(1)*x(1)+theta(1)*x(2);theta(2)*x(1)-x(2)-x(1)*x(3);-theta(3)*x(3)+x(1)*x(2)];