如何从Octave中的键盘读取功能并在以后使用?

问题描述

我正在用Octave编写脚本来计算球如何在表面弹跳。但是表面是由我必须从用户Input读取的函数定义的。 我有一行:

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

将我在终端中写的内容保存为'funcInput'变量的字符串。到目前为止一切顺利。
现在,我需要用此脚本中包含的其他变量替换此函数中的“ x”和“ y”,然后计算该函数的根。而且我不知道该怎么做...

稍后我要绘制一个表面,

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

它会产生错误

error: isinf: not defined for function handle

我猜这个函数不接受字符串作为参数,原因是当我这样做时:

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

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

解决方法

您可以使用<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>方法进行操作:

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

希望它会有用!

,

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,"s")
ezsurf( funcInput,10 ] )