Reputation: 11
I'm writing a script in Octave to calculate how will a ball bounce on a surface. But the surface is defined by a function that I have to read from user Input. I have a line:
funcInput = input("f(x,y) = ", "s")
that take what I write in terminal and save it as string to 'funcInput' variable. So far so good.
Now I need to substitute 'x' and 'y' in this function with other variables I have in this script, and then calculate roots of this function. And I have no idea how to do it...
Later I want to draw a surface so:
ezsurf(strcat('@(x, y) ', funcInput))
It produces an error
error: isinf: not defined for function handle
I guess this function does not take string as argument, cause when I do this:
ezsurf(@(x, y) (x.^2+y.^2)/10')
it works like a charm. So my question is: how can I make it work or what other way can I read function from user and use it later?
Upvotes: 1
Views: 350
Reputation: 22225
Octave provides the str2func
function for exactly this purpose.
(and also the inline
function which is similar, but this is headed for deprecation)
E.g.:
funcInput = input("f(x,y) = ", "s")
f = str2func( strcat( '@(x, y) ', funcInput ) )
ezsurf( f, [ -10, 10 ] )
Having said that, ezsurf
can indeed work directly from funcInput
. What you're doing wrong is that you're trying to convert it to a string that looks like an anonymous function. Don't, just plug the string directly:
funcInput = input("f(x,y) = ", "s")
ezsurf( funcInput, [ -10, 10 ] )
Upvotes: 1
Reputation: 362
You can do it using the eval
method:
funcInput = input('f(x, y) = ', 's');
eval(['func = @(x, y) (' funcInput ');']);
% Now the variable func is a function handle to the input function from the user
For example:
>> funcInput = input('f(x, y) = ', 's');
f(x, y) = x+4*y^2-2*x*y % user input
>> eval(['func = @(x, y) (' funcInput ');']);
>> func
func =
@(x, y) (x + 4 * y ^ 2 - 2 * x * y)
>> func(2, 3)
ans = 26
Hope it will be useful!
Upvotes: 1