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

前端 未结 4 1419
一个人的身影
一个人的身影 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:34

    If you broad intention is to have numeric values of certain symbolic expressions you have, for example, you have a larger program that generates symbolic expressions and you want to use these expression for numeric purposes, you can simply evaluate them using 'eval'. If their parameters have numeric values in the workspace, just use eval on your expression. For example,

    syms beta
    %n1,n2,m,aa= Constants
    % values to exemplify
    n1 = 1; n2 = 3; m = 1; aa = 5;
    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
    

    If beta has a value

    beta = 1.5;
    eval(beta)
    

    This will calculate the value of f for a particular beta. Using it as a function. This solution will suit you in the scenario of using automatically generated symbolic expressions and will be interesting for fast testing with them. If you are writing a program to find zeros, it will be enough using eval(f) when you have to evaluate the function. When using a Matlab function to find zeros using anonymous function will be better, but you can also wrap the eval(f) inside a m-file.

提交回复
热议问题