[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: inline functions (Corrected source)
From: |
Paul Kienzle |
Subject: |
Re: inline functions (Corrected source) |
Date: |
Sat, 10 Aug 2002 16:04:24 -0400 |
Sure. Add it to octave forge. I simplified the while loop a bit, and let
you use a default parameter of "x". I wouldn't go much beyond this in
terms of compatibility --- too many assumptions required about what makes a
variable and what order the variables should go in. Maybe inline(expr,n) as
shorthand for inline(expr,"x","P1","P2",...,"Pn") is useful.
Paul Kienzle
address@hidden
On Sat, Aug 10, 2002 at 06:37:46PM +0100, Etienne Grossmann wrote:
>
> Sorry, there was a part missing from the first attached func. Try
> the following.
>
> Etienne
>
> On Sat, Aug 10, 2002 at 01:32:42PM +0000, Steffan Berridge wrote:
> #
> # Hi,
> #
> # I have just started using Octave, having used Matlab for a
> # while. In Matlab I have often used inline functions, they
> # are very convenient for example when passing a function as
> # an argument.
> #
> # For example, the following is a function returning the
> # square of the argument:
> #
> # fun = inline('x^2','x');
> #
> # One can then pass this function as an argument to another
> # function:
> #
> # x = foo(fun,...);
> #
> # So my question is, is there an equivalent construction in
> # Octave? If not, what is the best way to pass functions as
> # arguments?
> #
> # Thanks,
> # Steffan
> --
> Etienne Grossmann ------ http://www.isr.ist.utl.pt/~etienne
## [fname,fcode] = inline (str,arg1,...) - Define a function from a string
##
## INPUT : -----------
## str : string : String defining the result of the function
## argN : string(s) : Names of the arguments of the function
##
## OUTPUT : ----------
## fname : string : Name of the new function, which can e.g. be called w/
## feval()
## fcode : string : The code of the function
##
## EXAMPLE : ---------
##
## fn = inline ("x.^2 + 1","x");
## feval (fn, 6)
## ans = 36
##
function [fname,fcode] = inline (str,varargin)
## Choose a name (naive way : won't work zillions of times)
while 1
fname = sprintf ("inline_func_%06i",floor (rand()*1e6));
if exist (fname), break; end
end
## construct arg list
if nargin == 1
argstr = "x";
else
argstr = sprintf ("%s,",all_va_args);
argstr = argstr(1:length(argstr)-1);
end
fcode = sprintf (["function r = %s (%s)\n",\
" r = ",str,";\n",\
"endfunction;"],\
fname, argstr);
eval (fcode);
endfunction
-------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL.
Octave's home on the web: http://www.octave.org
How to fund new projects: http://www.octave.org/funding.html
Subscription information: http://www.octave.org/archive.html
-------------------------------------------------------------