user7636697
user7636697

Reputation:

string input to anonymous function in MATLAB

In matlab i know i can convert string into anonymous function with str2func. For example;

s= '@(x) x.^2';
h= str2func(s);
h(2) would be 4

But what if i do not know the number of unknown? Let's say user of this program will enter lots of function to get a numerical solution of a system. When the user enters x^2, i should add @(x) to its beginning then convert it to a function. But in programming time i do not know how many function the user will enter with how many unknown. @(x) may should be @(x,y) as well as @(x,y,z). If the user enters the number of unknowns, how can i create and add the necessary prefix at runtime?

ps: number of unknown can be any integer number.

Upvotes: 1

Views: 266

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114518

  • You need to know not only the quantity of variables but also their names and order. An expression may read x(c). Even if you know that the expression has two variables in it and are able to parse out x and c, you won't be able to tell if the user intended to define something like @(x, c) x(c), @(c, x) x(c) or even something like @(c, d) x(c) where x is actually a function.
  • Parsing the expressions just to get the names they use is something that you shouldn't have to do.
  • Restricting the variable names that are allowed can be messy. If the user is expecting MATLAB syntax and you are parsing as MATLAB, why make your life harder? Also, when you introduce a restriction like one-letter variable names only, you have to ask yourself if there will ever be a situation where you need more than 27 variables.

It would be much safer all around to have the user list the names of the variables they plan on using before the function, e.g. (x, y, pi) pi*(x^2 + y). Now all you have to do is prepend @ and not worry about whether pi is a built-in or an argument. In my opinion the notation is quite clean.

Upvotes: 0

Related Questions