tags:

views:

646

answers:

3

In my matlab m-file I am using some logic (string concat) to build variables like this:

c = 'CalcPrediction(1,10)'

That means I have a string that is a function and some parameters. How can I do that function call?

Trying run(c) results in:

>> run(c)
??? Error using ==> run at 71
CalcPrediction(1,10) not found.

Note: run(c) works fine if there is no parameters. E.g. c='CalcPrediction'; run(c);

A: 

You want to use str2func. This function takes a string and returns a function handler that can be called with your parameters. Check out the examples on the linked page.

fh = str2func('CalcPrediction')
fh(1, 10)
ONODEVO
eval is a more accurate solution to the question. It takes as an input the exact string (in variable c) that markussvensson wants to use. (As an aside, the @-operator, as in fh=@CalcPrediction, is simpler than using str2func.)
SCFrench
+5  A: 

the command you are looking for is eval() instead of run()

M456
A: 

Without actually seeing the script it's hard to generalize, but...

Where squareRoot is an m-file containing only :y=sqrt(x)

Then executing :

x=[2,0];

c='squareRoot';

run(c);

gives :

y =

1.4142 0

This example is to say you can define the script to use a declared variable (x in this case) and then declare the variable before running the script.

Without the script I don't know what you're doing with the parameters. If this doesn't answer your question, post your script.

Neil D

related questions