本文介绍了如何在MATLAB中通过符号表达式创建函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过符号表达式创建函数?例如,我有以下内容:

How can I make a function from a symbolic expression? For example, I have the following:

syms beta
n1,n2,m,aa= Constants
u = sqrt(n2-beta^2);
w = sqrt(beta^2-n1);
a = tan(u)/w+tanh(w)/u;
b = tanh(u)/w;
f = (a+b)*cos(aa*u+m*pi)+a-b*sin(aa*u+m*pi);  %# The main expression

如果要在特殊程序中使用f来查找其零,如何将f转换为函数?或者,我该怎么做才能找到f的零以及此类嵌套表达式?

If I want to use f in a special program to find its zeroes, how can I convert f to a function? Or, what should I do to find the zeroes of f and such nested expressions?

推荐答案

您有几个选择...

如果您具有版本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的零,因此可以尝试使用 SOLVE 函数用于符号方程式:

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');

这篇关于如何在MATLAB中通过符号表达式创建函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:59