computing a interpolating polynomial for some function

3 次查看(过去 30 天)
I am trying to understand how to use the commands polyfit and polyval so i am trying to interpolate some function, I wrote something so simple but even it is simple it gives me error
x=linspace(-1,1,20);
y= @(x) 1/(1+16*(x^2));
p = polyfit (x,y,2);
plot(x,p)
and this is the error message
Error using polyfit (line 48)
The first two inputs must have the same number of elements.
Error in polyfit_polyval (line 7)
p = polyfit (x,y,2);

采纳的回答

Torsten
Torsten 2022-1-26
编辑:Torsten 2022-1-26
x = linspace(-1,1,20);
yfunc = @(x) 1./(1+16*x.^2);
y = yfunc(x);
...
or
x=linspace(-1,1,20);
y=1./(1+16*x.^2);
...
  9 个评论
Steven Lord
Steven Lord 2022-1-26
In your original code, the main problem was that y was a function handle but polyfit requires its first two inputs to be numeric arrays of the same size. Note that Torsten defined the function not as y but as yfunc then evaluated yfunc with x as the input to generate y. So the data that got passed into polyfit as its second input was the result of evaluating that function at the points in x rather than the function.
The use of the element-wise operators allowed the function to be evaluated on an array and return an array with the same size. The matrix form of the operator would require the inputs to be square matrices.
A = [1 2; 3 4]
A = 2×2
1 2 3 4
y = A.*A % each element of y is the square of the corresponding element of A
y = 2×2
1 4 9 16
z = A*A % this perform matrix multiplication instead of element-wise
z = 2×2
7 10 15 22

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Polynomials 的更多信息

产品


版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by