title: Solving the Linear Regression Model using QR Decomposition (MATLAB)
body: <p><strong>Background</strong> : I want to implement a MATLAB algorithm that takes as input vectors x and y, solves the linear regression problem
  associated with the data stored in x and y using a modified QR version and then to plot the graph of the linear function.</p>
  <p>So first I wrote the modified QR algorithm :</p>
  <pre><code>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
  </code></pre>
  <p>Then I wrote the algorithm for the linear regression :</p>
  <pre><code>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
  </code></pre>
  <p>I tried to run this algorithm on the following data :</p>
  <pre><code>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];
  </code></pre>
  <p>The full error message that I received is :</p>
  <pre><code>        Index in position 2 exceeds array bounds (must not exceed 2).
          Error in untitled&gt;backward (line 12)
          x(n)=y(n)/U(n,n);
          Error in untitled&gt;QRQ (line 8)
          x=backward(R1,c1,n);
          Error in untitled&gt;LinearReg (line 20)
          z=QRQ(A,y,2);
  </code></pre>
  <p>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 &gt;2, hence the error.
  Using the debugger, I see that U is a 21x2 array, and n has a value of 21.</p>
  <p>How can this MATLAB algorithm be fixed?</p>