Creating Least Square Function

4 views (last 30 days)
hsquaredd
hsquaredd on 19 Aug 2017
Commented: hsquaredd on 20 Aug 2017
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')

Answers (1)

Image Analyst
Image Analyst on 19 Aug 2017
Edited: Image Analyst on 19 Aug 2017
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 Comment
hsquaredd
hsquaredd on 20 Aug 2017
Thanks for the support. We are not allowed to use the polyfit function for the lab.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!