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

조회 수: 1 (최근 30일)
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
  댓글 수: 1
Walter Roberson
Walter Roberson 2016년 10월 19일
편집: James Tursa 2016년 10월 19일
What is the error message?
You should firmly avoid using sum as the name of a variable, as it is the name of a key MATLAB function -- a function you might want to use in that code.
By the way:
L(i,1:i-1) * y(1:i-1)
will give you the sum without any for loop.

댓글을 달려면 로그인하십시오.

채택된 답변

James Tursa
James Tursa 2016년 10월 19일
편집: James Tursa 2016년 10월 19일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Testing Frameworks에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by