MATLAB: Attempted to access q(1,3); index out of bounds because size(q)=[2,2]. Error in vactora_1 (line 10) ;q(j-1,i) = q(i,j);

errorindexout of bound

Hi, I am working on below code to find Gram-Schmidt equation. Below is a part of the equation that will lead me. I am finding an error as stated above in the question. Please help, If you can find the problem. Error is : Attempted to access q(1,3); index out of bounds because size(q)=[2,2]. Error in vactora_1 (line 10)
q(j-1,i) = q(i,j);
n = 3; %dimension for A
A = [1,-1,1; 1,0,3; 2,1,-5]; % A represnets vectors [v1,v2.....Vn]
B=A;
q = zeros(n-1,n-1); %dimension of matrix
for j = 2:n
sum = A(:,j);%
for i = 1:j-1
q(j-1,i) = q(i,j);
sum = sum - q(j-1,i)*B(:,j-1);
end
B(:,j) = sum;
end

Best Answer

q is meaningless here. Even if the dimension would be correct, it contains zeros only. In consequence q(j-1,i)*B(:,j-1) is 0 in every case. You have to update q anywhere to differ from 0. And it needs to be a [n x n] matrix, not [n-1 x n-1].
Check the algorithm again, e.g.: