如何在Octave中读取键盘上的函数并在以后使用



我正在Octave中编写一个脚本来计算球在曲面上的反弹方式。但是曲面是由一个函数定义的,我必须从用户Input中读取该函数。我有一条线路:

funcInput = input("f(x,y) = ", "s")

将我在终端中所写的内容作为字符串保存到"funcInput"变量中。到目前为止还不错
现在我需要用这个脚本中的其他变量替换这个函数中的"x"one_answers"y",然后计算这个函数的根。我不知道怎么做…

稍后我想画一个表面,所以:

ezsurf(strcat('@(x, y) ', funcInput))

它会产生错误

error: isinf: not defined for function handle

我想这个函数不把字符串作为参数,因为当我这样做时:

ezsurf(@(x, y) (x.^2+y.^2)/10')

它就像一个符咒。所以我的问题是:我如何让它工作,或者我可以通过什么其他方式从用户那里读取函数并在以后使用它?

您可以使用eval方法:

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

例如:

>> 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

希望它有用!

Octave正是为此目的提供str2func函数
(还有类似的inline功能,但这将被弃用(

例如:

funcInput = input("f(x,y) = ", "s")
f = str2func( strcat( '@(x, y) ', funcInput ) )
ezsurf( f, [ -10, 10 ] )

话虽如此,ezsurf确实可以直接从funcInput工作。你做错的是,你试图将它转换成一个看起来像匿名函数的字符串。不要,直接插入字符串即可:

funcInput = input("f(x,y) = ", "s")
ezsurf( funcInput, [ -10, 10 ] )

最新更新