help-octave
[Top][All Lists]
Advanced

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

Re: Most elegant way to pass parameters to functions that are used as ha


From: Daniel Kraft
Subject: Re: Most elegant way to pass parameters to functions that are used as handles?
Date: Thu, 16 Jul 2015 07:01:59 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.7.0

Hi!

On 2015-07-15 22:25, Markus Appel wrote:
> On 07/15/2015 10:14 PM, rocketsound wrote:
>> For example take the fmincon function (currently only awailable in Matlab) 
>> doc fmincon <http://de.mathworks.com/help/optim/ug/fmincon.html>  . It takes
>> two handles: one for the objective function and one for the constraints.
>>
>> I'm curious about what you think is the most clean and efficient way to pass
>> parameters I use in those functions used as handles.
>>
>> At the moment I'm stuck with two solutions:
>> 1) Use global variables, a very bad solution
>> 2) Use nested functions, but because of the odd scoping rules I have to
>> declare all variables I use like in the good old C times and I somehow
>> dislike this
>> 3) ?
>>
> 
> How about anonymous functions, as also suggested in the mathworks link?
> 
>> x = fmincon(@(x)norm(x)^2,x0,A,b);
> 
> You can use it to wrap any function and pass variables from the current
> scope:
> 
>> par1 = 42;
>> par2 = "anything";
>> x = fmincon( @(x) my_obj_fun(x,par1,par2), x0, A, b);

This is also what I use, and I find it quite elegant.  It is nice that
Octave allows such "semi closures".

Earlier, I mostly used global variables for these purposes -- but I've
now almost entirely eliminated them in favour of using this construct.

In case you have to pass around a larger "state" of some sort, you can
also wrap everything into a struct before constructing the closure with
just the struct.

Yours,
Daniel

-- 
http://www.domob.eu/
OpenPGP: 1142 850E 6DFF 65BA 63D6  88A8 B249 2AC4 A733 0737
Namecoin: id/domob -> https://nameid.org/?name=domob
--
Done:  Arc-Bar-Cav-Hea-Kni-Ran-Rog-Sam-Tou-Val-Wiz
To go: Mon-Pri

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

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