MATLAB: For some reason every time I try to test the forward elimination function there is an error in the sum part, I cannot figure out why or what else I need to ad

forwardguassian

function [ y ] = forward_elim( L, b )
%performs gaussian foward elimination solving Ly=b using specific
%algorithm given
% Detailed explanation goes here
n = length(b);
y= zeros (n,1);
for i = 1:n
i = i+1;
%check to see that L is a valid matrix
if size (L) == size(L') % testing to see that L is a square matrix
if isnan(L) % if there is a not real number terminate
disp('error: invalid inputs in L')
break
elseif diag(L) == 0 % if a diagnol element of the matrix is 0 terminate
disp ('error: A diagnol element of L = 0')
break
end
else
disp('error: L is not a suqare matrix')
break
end
sum = 0;
for j = 1:i-1
sum = sum + L(i,j)*y(j);
end
y(i) = (b(i)- sum)/L(i,i) ;
end
end

Best Answer

Looks like you are incrementing the i index variable twice ... once as a for-loop index and once explicitly:
for i = 1:n
i = i+1; % <-- You should probably delete this line
Also, you might consider moving your L checks outside of your for-loop. There is no need to do these checks over and over again for each iteration. Just once prior to the for-loop would be sufficient. And some of these tests should change:
if isnan(L)
should be
if any(isnan(L(:)))
and
elseif diag(L) == 0
should be
elseif any(diag(L) == 0)
Finally, I would advise against using just a message with a break when you encounter an error, as this will still return a garbage value to the caller. Instead, actually force an error. E.g., change this:
disp('error: invalid inputs in L')
break
to this
error('invalid inputs in L')
And same for all of your other error catches.