简体   繁体   中英

Symbolic derivatives throwing error in older versions of MATLAB

I have this MATLAB code that uses symbolic functions for certain operations and the sym/diff function throws a very annoying error when I run it in the 2015b version in my server. My laptop with 2018a runs the same code with no problems. The error in particular is:

Error using sym/diff (line 68)
Error using class
The first argument to function CLASS must be a struct.

An MWE of the part of the code that's throwing the error is the following:

Thrust_fcn = @(r) 5 * exp(-2*r)
syms r;
diff_fcn = diff(Thrust_fcn, r);

This is the code in the built-in sym/diff function that's throwing the error:

try
    if nargin == 1
        r = class(maplemex(0,'MTM:-diff',m),'sym');
    elseif nargin == 2
        r = class(maplemex(0,'MTM:-diff',m,n),'sym');
    else
        r = class(maplemex(0,'MTM:-diff',m,n,u),'sym');
    end
catch
    error(lasterr);
end

I've checked the code of the sym/diff function on 2018a and is completely different, it is a ~300 lines piece of code.

Any ideas on how to get this to work? Thanks a lot!

Symbolic Function

When you use @(r) , you're generating a function_handle , which is not part of the Symbolic toolbox:

>> Thrust_fcn = @(r) 5 * exp(-2*r);
>> whos Thrust_fcn
  Name            Size            Bytes  Class              Attributes
  Thrust_fcn      1x1                32  function_handle  

Instead, try creating r first, and making Thrust_fcn using the sym r

>> syms r;
>> Thrust_fcn = 5 * exp(-2*r); %%% Not using @(r)! %%%

>> whos Thrust_fcn
  Name            Size            Bytes  Class    Attributes
  Thrust_fcn      1x1                 8  sym   

Now that Thrust_fcn is a sym, try calling diff(Thrust_fcn, r)

Calling MuPAD's Function (Within MATLAB)

If you'd like to continue using a function handle, you can use MuPAD's functionality while remaining within the MATLAB editor. This MathWorks Documentation page explains a few ways to use MuPAD's functions, but I'll provide a working example:

% Notice that 'syms r' is never called.
% You may want to ensure your previous variable 'r' has been cleared first.
clear r;

Thrust_fcn = @(r) 5 * exp(-2*r);
feval(symengine,'diff',Thrust_fcn,'r')

This acts the same way as if you were to define a function in MuPAD, and call diff on Thrust_fcn with the input 'r' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM