为了泛化的目的,我希望Matlab能够自动计算第一个&关联函数f(x(的二阶导数。(在我将f(x(=sin(6x(更改为f(x(x(=sin(8x(的情况下(
我知道存在名为diff()
和syms
的内置命令,但我不知道如何使用for循环中的索引i
来处理它们。这是我正在努力解决的关键问题。
如何更改以下代码集?我使用的是MATLAB R2019b。
n = 10;
h = (2.0 * pi) / (n - 1);
for i = 1 : n
x(i) = 0.0 + (i - 1) * h;
f(i) = sin(6 * x(i));
dfe(i) = 6 * cos(6 * x(i)); % first derivative
ddfe(i) = -36 * sin(6 * x(i)); % second derivative
end
您可以简单地使用subs
和double
来完成此操作。对于您的案例:
% x is given here
n = 10;
h = (2.0 * pi) / (n - 1);
syms 'y';
g = sin(6 * y);
for i = 1 : n
x(i) = 0.0 + (i - 1) * h;
f(i) = double(subs(g,y,x(i)));
dfe(i) = double(subs(diff(g),y,x(i))); % first derivative
ddfe(i) = double(subs(diff(g,2),y,x(i))); % second derivative
end
通过@Daivd评论,您也可以对循环进行矢量化:
% x is given here
n = 10;
h = (2.0 * pi) / (n - 1);
syms 'y';
g = sin(6 * y);
x = 0.0 + ((1:n) - 1) * h;
f = double(subs(g,y,x));
dfe = double(subs(diff(g),y,x)); % first derivative
ddfe = double(subs(diff(g,2),y,x)); % second derivative