1

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.

12
  • 2
    The problem is not just detecting how many variables the user entered; you also need to detect their names. Is there some pattern? Can the user enter something like cos(x)? Can variable names have more than one letter? Commented Nov 23, 2017 at 22:01
  • 1
    @ssovukluk. Variable names are very important. You had better not prepend @(x) to y.^2. That's why it is much cleaner for the user to spec out what names they want to use first. Perhaps you should just prepend the @. Commented Nov 23, 2017 at 22:10
  • 1
    Order of the variables is important. @(x,y) x.^y is very different from @(y,x) x.^y Commented Nov 23, 2017 at 22:12
  • 2
    I'd use regexp and some sprintf. But how do you decide if by x^2+y^3 the user meant @(x,y) x^2+y^3 or @(y,x) x^2+y^3? they are different function Commented Nov 23, 2017 at 22:23
  • 1
    What happens when you have a polynomial of 27 variables (or 28 if you count underscores)? Commented Nov 23, 2017 at 22:25

1 Answer 1

0
  • 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.