Creating Least Square Function

2 次查看(过去 30 天)
hsquaredd
hsquaredd 2017-8-19
评论: hsquaredd 2017-8-20
Hello everyone. I am tasked to create a function that will receive two vectors and apply polynomial fitting based on the least squares method. In class we were given this code to build off of. Unfortunately, I'm having difficulty understanding it.
function b=inclasslab5(x,y,m)
%x=vector, y=vector, m=desired data points
if length(x)~=length(y)
error(' ')
elseif m+1>length(x)
error(' ')
%Does this make sure the vectors can multiply?
else
end
a=zeros(m+1);
d=zeros(m+1,1);
for j1=1:m+1
for j2=1:m+1
a(j1,j2)=sum(x.n*(2*m+2-j1*j2))
end
end
for j1=1:m+1
d(j1)=sum(x.n*(m+1-j1)*y)
end
c=rref([a,d])
b=c(:,m+2)
When I apply the given vectors, I get the following error message: "Struct contents reference from a non-struct array object. Error in inclasslab5 (line 16): a(j1,j2)=sum(x.n*(2*m+2-j1*j2))". I'm almost certain it has to do with the value n.
Ultimately, this value b needs to be applied to my script file which plots the data.
clc
x=[1.5 -2.3 5 -4 7 -1 3 0.8 -2 4.2 1.3 1.4 0 0.9 1.7 -4]
y=[-0.1 1.2 3.4 -4 3 -1.5 3.3 5.2 0.7 7 -3 9 4 8 2 7]
%raw data points
xmin=min(x)
xmax=max(x)
x1=linspace(xmin,xmax)
%linspace creates linearly spaced vectors
y1=b(1)*x1+b(2)
%this creates line
y2=b(1)*x1.^2+b(2)*x1+b(3)
%this creates parabola
y3=b(1)*x1.^3+b(2)*x1.^2+b(3)*x1+b(4)
%this creates cubic parabola
plot(x,y,'o',x1, y1,'b',x1,y2,'r',x1,y3,'g')

回答(1 个)

Image Analyst
Image Analyst 2017-8-19
编辑:Image Analyst 2017-8-19
When you say x.n, you're assuming that x is a structure and that it has a field called "n". Evidently, from the error message, x is not a structure.
You need to figure out what it's doing and replace the x.n with the proper expression or variable.
You can get rid of everything they have there except the function line and do this:
function b = inclasslab5(x, y, m)
b = polyfit(x, y, m);
My standard demo is attached.
  1 个评论
hsquaredd
hsquaredd 2017-8-20
Thanks for the support. We are not allowed to use the polyfit function for the lab.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Get Started with Curve Fitting Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by