写在前面
我们在建立模型时,有时候一段程序的最终目标是输出一个多项式,或者说,输出一个多项式系数矩阵,当我们使用matlab编写程序来实现这个功能时,conv()和poly()这两个函数是非常常见的。下面,我将使用编写拉格朗日插值多项式系数的输出为例来讲讲这两个函数。
拉格朗日插值实验
要求:
1.输入自变量向量
和对应的函数值向量
,进行拉格朗日插值,插值多项式的最高阶次数应当为自变量向量
里的元素个数减1。
2.输出拉格朗日多项式的系数矩阵。
代码如下:
function [C] = lagran(X,Y)
%Input X is a vector that contains a list of abscissas
% Y is a vector that contains a list of ordinates
%Output C is a matrix that contains the coefficients of the Lagrange
%interpolatory polynomial
% L is a matrix that contains the Lagrange coefficient polynomials
w = length(X);
n = w-1;
L = zeros(w,w);
%From the Lagrange coefficient polynomials
for k = 1:n+1
V = 1;
for j = 1:n+1
if k ~=j
V = conv(V,poly(X(j)))/(X(k)-X(j));
end
end
L(k,:) = V;
end
%Determine the coefficients of the Lagrange interpolating polynomial
C = Y*L;
end
这段代码最重要的是这里编造多项式系数的部分:
for k = 1:n+1
V = 1;
for j = 1:n+1
if k ~=j
V = conv(V,poly(X(j)))/(X(k)-X(j));
end
end
L(k,:) = V;
end
我们看到了poly()与conv()的结合使用
poly()
Polynomial with specified roots or characteristic polynomial
由输入的不同分为两种用法
1.p = poly(x)(其中 x 是向量)返回多项式的系数,其中多项式的根是 x 的元素
2.p = poly(A)(其中 A 是 n×n 矩阵)返回矩阵 det(λI – A) 的特征多项式的 n+1 个系数。
conv()
Convolution and polynomial multiplication
这里只介绍一种用法
w = conv(u,v) 返回向量 u 和 v 的卷积。如果 u 和 v 是多项式系数的向量,对其卷积与将这两个多项式相乘等效。
于是完成了一轮内循环后,最终会输出拉格朗日多项式一项 的系数。