如何在 matlab 中区分内联函数

How do I differentiate an inline function in matlab

假设我在 matlab 中编写以下内容

c='x^2-6';
f=inline(c);

那么f就是一个内联函数。我可以通过输入

来计算不同值的 f
f(2)
f(5)

但是,当我尝试 diff(f) 时,它没有 return 2*x。我怎样才能从 f 得到 2*x

您不能使用 inline 对象进行符号数学计算。改为使用 sym 个对象:

c= sym('x^2-6'); % creates the 'sym' object
subs(c,2) % calculates c(2)
diff(c);

另请注意 inline will be removed 在未来的版本中

您需要 MATLAB Symbolic Toolbox。您所描述的称为符号微分。 (还有符号积分等)。 "normal"(非符号)版本的 MATLAB 旨在进行数值计算,而不是微积分或代数运算。

这是一个符号方法,将函数和参数作为用户输入并进行区分。

clear;
clc;
v=input('Parameter :');%input for example 'x' and remember the quotes
syms(v);%symbolic variable : x in this case
y=input('function :');%example exp (x) ,not exp(y) or ay other variable
f=matlabFunction(y);%converts y to a command type function f
df = matlabFunction(diff(y)); %calculates the differentiation.

现在,如果您执行类似 f(1) 的操作,它将显示 2.71828,而 df(1) 将显示 2.71828