Index in position 2 exceeds array bounds (must not exceed 2

3 vues (au cours des 30 derniers jours)
Tarek Hajj Shehadi
Tarek Hajj Shehadi le 12 Fév 2021
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!

Réponse acceptée

Cris LaPierre
Cris LaPierre le 12 Fév 2021
Modifié(e) : Cris LaPierre le 12 Fév 2021
The full error message is
Index in position 2 exceeds array bounds (must not exceed 2).
Error in untitled>backward (line 12)
x(n)=y(n)/U(n,n);
Error in untitled>QRQ (line 8)
x=backward(R1,c1,n);
Error in untitled>LinearReg (line 20)
z=QRQ(A,y,2);
The line causing the error is x(n)=y(n)/U(n,n);
  • the only variable with an index in position 2 is U. Apparently U only has 2 columns, and n is a value >2, hence the error.
Using the debugger, I see that U is a 21x2 array, and n has a value of 21.
U = rand(21,2);
U(3,3)
Index in position 2 exceeds array bounds (must not exceed 2).

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by