例如 f(x) = x^3 -2x -5 ,用一个矩阵接收他们的系数表示一个多项式 --> p = [1 0 -2 5];
Plot the polynomial 给出定义域画图 for -2<=x<=5
polyval(多项式,定义域) 通过定义域和多项式 生成多项式函数
a = [9,-5,3,7]; x = -2:0.01:5;
f = polyval(a,x);
plot(x,f,'LineWidth', 2);
xlabel('x'); ylabel('f(x)');
set(gca, 'FontSize', 14)
微分:polyder(多项式) --> 返回一个新的多项式 代表原来函数的微分
如果要求一个点的微分
两个多项式相乘时,两个多项式用两个矩阵接收,利用conv卷积函数进行合并
diff() 计算单行矩阵 每个元素之间的差 (Δ)
x = [1 2 5 2 1];
diff(x)
ans = 1 3 -3 -1
两点连线之间的斜率
x = [1 2]; y = [5 7]; %代表的不是两个点,而是两个点的x,y坐标 两个点为(1,5),(2,7)
slope = diff(y)./diff(x) %y = y2 -y1 ;x = x2 - x1;
f(x)= sinx 在 pi/2处 h=0.1的微分
x0 = pi/2; h = 0.1;
x = [x0 x0+h];
y = [sin(x0) sin(x0+h)];
m = diff(y)./diff(x)
f(x) 在(0,2π) 的微分
for example:
h = 0.5; x = 0:h:2*pi;
y = sin(x); m = diff(y)./diff(x);
g = colormap(lines); hold on;
for i=1:4
x = 0:power(10, -i):pi;
y = sin(x); m = diff(y)./diff(x);
plot(x(1:end-1), m, 'Color', g(i,:));
end
hold off;
set(gca, 'XLim', [0, pi/2]); set(gca, 'YLim', [0, 1.2]);
set(gca, 'FontSize', 18); set(gca, 'FontName', 'symbol');
set(gca, 'XTick', 0:pi/4:pi/2);
set(gca, 'XTickLabel', {'0', 'p/4', 'p/2'});
h = legend('h=0.1','h=0.01','h=0.001','h=0.0001');
set(h,'FontName', 'Times New Roman'); box on;
由于微分会减少一项,所以二阶微分的自变量x也应该少一个
x = -2:0.005:2; y = x.^3;
m = diff(y)./diff(x);
m2 = diff(m)./diff(x(1:end-1));
h = 0.05; x = 0:h:2;
midpoint = (x(1:end-1)+x(2:end))./2;
y = 4*midpoint.^3;
s = sum(h*y) %s 即为 4x^3从0-2的积分
h = 0.05; x = 0:h:2; y = 4*x.^3;
s = h*trapz(y)
或者
h = 0.05; x = 0:h:2; y = 4*x.^3;
trapezoid = (y(1:end-1)+y(2:end))/2;
s = h*sum(trapezoid)
h = 0.05; x = 0:h:2; y = 4*x.^3;
s = h/3*(y(1)+2*sum(y(3:2:end-2))+...
4*sum(y(2:2:end))+y(end))
写一个函数,传递函数指针和定义域作为参数,可以直接绘制函数指针指向的函数的图像。
function [y] = xy_plot(input,x)
% xy_plot receives the handle of a function
% and plots that function of x
y = input(x); plot(x,y,'r--');
xlabel('x'); ylabel('function(x)');
end
y = @(x) 1./(x.^3-2*x-5); %一重积分求面积
integral(y,0,2) %传参:函数指针,下限,上限
f = @(x,y) y.*sin(x)+x.*cos(y); %二重积分求体积
integral2(f,pi,2*pi,0,pi) %传参: 函数指针,下限,上限,下限,上限
f = @(x,y,z) y.*sin(x)+z.*cos(y);
integral3(f,0,pi,0,1,-1,1)