clc
clear all
x= -2:0.1:4;
y= (3*x.^3)-(26*x)+10;
y1= diff(y)./diff(x);
y2= diff(y1)./diff(x);
plot(x,y,'R')
hold on
plot(x,y1,'G')
hold on
plot(x,y2,'B')
这是找到二阶导数的正确方法吗? 它没有找到二阶导数并给出一个矩阵维必须在第6行中达成一致的错误。
答案 0 :(得分:0)
您的值y
对应于值x
。在计算y1
的一阶导数y
的近似值时,使用有限差分。这些有限差分在x
之间的点处最接近导数。这意味着您计算二阶导数的近似值应该包含(x(1:end-1)+x(2:end))/2
:
x1 = (x(1:end-1) + x(2:end))/2;
y2 = diff(y1) / diff(x1);
请注意,这些近似值y2
最接近位置x2 = (x1(1:end-1) + x1(2:end))/2
的二阶导数。
总而言之,您的代码可能如下所示:
%// Clear command window, delete all variables, close all figures
clc;
clear all;
close all;
%// Define function
f = @(x) (3*x.^3)-(26*x)+10;
%// Define positions
x = -2:0.1:4;
%// Calculate f(x)
y= f(x);
%// Calculate approximation to first derivative and their positions
x1 = (x(1:end-1) + x(2:end))/2;
y1 = diff(y) ./ diff(x);
%// Calculate approximation to second derivative and their positions
x2 = (x1(1:end-1) + x1(2:end))/2;
y2 = diff(y1) ./ diff(x1);
%// Plot
plot(x, y, 'R',...
x1,y1,'G',...
x2,y2,'B');
legend('f','f''', 'f''''');