如何在matlab中集成这个函数

问题描述 投票:0回答:2

我是 matlab 新手。

如何整合这行代码? ?

p2= polyfit(x,y,length(x));
from= x(1);
to= x(length(x));

我需要整合

p2

我尝试了很多集成功能:

 value = integral(p2,from,to);

但是我得到了

使用积分时出错(第 82 行)第一个输入参数必须是函数 手柄。

Error in poly_integral (line 5)
 value = integral(p2,from,to);
matlab numerical-integration
2个回答
0
投票

那是因为

p2
在您的代码中不是一个函数。它只是一个系数向量。
integral
的第一个参数需要处理您要集成的函数。

从您的代码来看,您似乎想要定义一个计算多项式的函数

p2
。如果是这样,您可以执行以下示例所示的操作:

% take an example set of x and y 
x = linspace(0, pi, 1000); % uniform samples between 0 to pi
y = sin(x); % assume, for sake of example, output is sine function of input

% polynomial fit
p2 = polyfit(x,y,4); % 4th order polynomial
% Note that, in general, the order should be much smaller than length(x).
% So you probably should review this part of your code as well.

% define a function to evaluate the polynomial
fn = @(x) polyval(p2, x);
% this means: fn(x0) is same as polyval(p2, x0)

% compute integral
value = integral(fn,x(1),x(end));

0
投票

您可以使用

polyint
函数获取多项式系数以精确积分多项式:

p2  = polyfit(x,y,length(x));
int = diff(polyval(polyint(p2),x([1 end])));
© www.soinside.com 2019 - 2024. All rights reserved.