How do I make a function from a symbolic expression in MATLAB?

前端 未结 4 1407
一个人的身影
一个人的身影 2021-01-05 06:59

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         


        
4条回答
  •  耶瑟儿~
    2021-01-05 07:30

    You have a couple of options...

    Option #1: Automatically generate a function

    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)
    

    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
    

    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.


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

提交回复
热议问题