Thread Subject: Anonymous function creation from string

Subject: Anonymous function creation from string

From: Nick Denman

Date: 19 Mar, 2008 12:37:02

Message: 1 of 3

Hi

I have a GUI where the user can enter a function (as a
string) that is evaluated in another routine. For example,
the user may enter 'theta(1)*x^2 - theta(2)*x^3'.

Currently I convert the above string expression to an
anonymous function by using EVAL, e.g.
>> fHnd = eval(['@(x,theta) (',str,')'])
where str is the string given in the GUI. Can anyone suggest
a better way of creating the anonymous function without
using eval?

Cheers,
Nick

Subject: Anonymous function creation from string

From: Christophe Boudrie

Date: 19 Mar, 2008 12:49:01

Message: 2 of 3

Hi,

You can directly evaluate the user string as far as all
inputs ("theta", "x"...) are in your current workspace...

For instance,
theta=[2 3];
a=1;

try
  my_result=eval('theta(1)*x^2 - theta(2)*x^3');
catch
  disp('Unable to evaluate user expression')
end

If the user expression is a simple matlab function, you can
then use "str2func" function.

regards, chris

"Nick Denman" <ngdenmanNOSPAM@gmail.REMOVETHIS.com> wrote
in message <frr1de$7a5$1@fred.mathworks.com>...
> Hi
>
> I have a GUI where the user can enter a function (as a
> string) that is evaluated in another routine. For example,
> the user may enter 'theta(1)*x^2 - theta(2)*x^3'.
>
> Currently I convert the above string expression to an
> anonymous function by using EVAL, e.g.
> >> fHnd = eval(['@(x,theta) (',str,')'])
> where str is the string given in the GUI. Can anyone
suggest
> a better way of creating the anonymous function without
> using eval?
>
> Cheers,
> Nick

Subject: Anonymous function creation from string

From: Loren Shure

Date: 20 Mar, 2008 13:38:37

Message: 3 of 3

In article <frr1de$7a5$1@fred.mathworks.com>,
ngdenmanNOSPAM@gmail.REMOVETHIS.com says...
> Hi
>
> I have a GUI where the user can enter a function (as a
> string) that is evaluated in another routine. For example,
> the user may enter 'theta(1)*x^2 - theta(2)*x^3'.
>
> Currently I convert the above string expression to an
> anonymous function by using EVAL, e.g.
> >> fHnd = eval(['@(x,theta) (',str,')'])
> where str is the string given in the GUI. Can anyone suggest
> a better way of creating the anonymous function without
> using eval?
>
> Cheers,
> Nick
>
not sure it will work in your case, but look into str2func.

--
Loren
http://blogs.mathworks.com/loren/

Tags for this Thread

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Tag Activity for This Thread
Tag Applied By Date/Time
anonymous function Nick Denman 19 Mar, 2008 08:40:20
eval Nick Denman 19 Mar, 2008 08:40:20
rssFeed for this Thread

Contact us at files@mathworks.com