且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在MATLAB中通过符号表达式创建函数?

更新时间:2021-11-16 01:43:56

您有几个选择...

如果您具有版本4.9(R2007b +)或符号工具箱的更高版本,您可以将符号表达式转换为匿名函数或使用 matlabFunction 的功能M文件> 函数.文档中的示例:

If you have version 4.9 (R2007b+) or later of the Symbolic Toolbox you can convert a symbolic expression to an anonymous function or a function M-file using the matlabFunction function. An example from the documentation:

>> syms x y
>> r = sqrt(x^2 + y^2);
>> ht = matlabFunction(sin(r)/r)

ht = 

     @(x,y)sin(sqrt(x.^2+y.^2)).*1./sqrt(x.^2+y.^2)

选项2:手动生成函数

由于您已经编写了一组符号方程式,因此只需将部分代码剪切并粘贴到函数中即可.这是您上面的示例所示:

Option #2: Generate a function by hand

Since you've already written a set of symbolic equations, you can simply cut and paste part of that code into a function. Here's what your above example would look like:

function output = f(beta,n1,n2,m,aa)
  u = sqrt(n2-beta.^2);
  w = sqrt(beta.^2-n1);
  a = tan(u)./w+tanh(w)./u;
  b = tanh(u)./w;
  output = (a+b).*cos(aa.*u+m.*pi)+(a-b).*sin(aa.*u+m.*pi);
end

调用此函数f时,必须输入beta的值和4个常量,它将返回评估主表达式的结果.

When calling this function f you have to input the values of beta and the 4 constants and it will return the result of evaluating your main expression.

注意::由于您还提到要查找f的零,因此可以尝试使用

NOTE: Since you also mentioned wanting to find zeroes of f, you could try using the SOLVE function on your symbolic equation:

zeroValues = solve(f,'beta');