Index in position 2 exceeds array bounds (must not exceed 2
Show older comments
Background : I am writing a MATLAB algorithm LinearReg that takes as an input the vectors x and y and solves the linear regression problem associated with the data stored in x and y using a version
decomposition that I wrote and then plots the data and the obtained line using plot(x,y,’bo’,x,ysol,’g-’). It should output ysol, the vector of y coordinates of the obtained line at the x points.
- First, I wrote the modified
algorithm as follow :
function x=QRQ(A,b,n)
[Q1,R1]=qr(A);
c1=Q1'*b;
n=length(c1);
x=backward(R1,c1,n);
end
function x=backward(U,y,n)
x=zeros(n,1);
x(n)=y(n)/U(n,n);
for i=n -1 : -1 : 1
x(i)=(y(i)-U(i,i+1 : n)*x(i+1 : n))/U(i,i);
end
end
- The second and vital part is writing the MATLAB function LinearReg that should solve and plot the graph of the linear function :
function ysol = LinearReg(x,y)
A=[x ones(21,1)];
z=QRQ(A,y,2);
ysol=z(1)*x+z(2);
plot(x,y,'bo',x,ysol,'g-');
end
Running this code using the following data points :
x=[0;0.25;0.5;0.75;1;1.25;1.5;1.75;2;2.25;2.5;2.75;3;3.25;3.5;3.75;4;4.25;4.5;4.75;5];
y=[4;3;7;7;1;4;4;6;7;7;2;6;6;1;1;4;9;3;5;2;7];
have resulted in an error stating that Index in position 2 exceeds array bounds (must not exceed 2). I am afraid that my mistake is something trivial or stupid. I hope someone assists me in functioning this code. Thank you very much!
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing 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!