Got Questions? Get Answers.
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Call function from string

Subject: Call function from string

From: Aron Sceidt

Date: 27 May, 2011 15:14:04

Message: 1 of 2

Is it possible to call a function whose name is stored in a string?

For example imagine that I have a function saved with a name "addTwo()" and I have a variable x = "addTwo". Is it possible to execute the function "addTwo" from x in some way? possibly also adding parameters to it?

Subject: Call function from string

From: someone

Date: 27 May, 2011 18:30:21

Message: 2 of 2

"Aron Sceidt" <sigarru87@gmail.com> wrote in message <irof3s$cev$1@newscl01ah.mathworks.com>...
> Is it possible to call a function whose name is stored in a string?
>
> For example imagine that I have a function saved with a name "addTwo()" and I have a variable x = "addTwo". Is it possible to execute the function "addTwo" from x in some way? possibly also adding parameters to it?

% One VERY BAD WAY is to use the evil "eval" command.
% But I suggest not using it.

% Another way is to use function handles and the "str2func" commands:

>> x = 'addTwo'

x =

addTwo

>> fh = str2func(x)

fh =

    @addTwo

% See the MATLAB help:

doc str2func

% and then click on "function handle" in the See Also Section.

Tags for this Thread

No tags are associated with this thread.

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.

Contact us