Reputation:
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
Reputation: 114518
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.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