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 visualizzazione (ultimi 30 giorni)
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 Commento
Walter Roberson
Walter Roberson il 19 Ott 2016
Modificato: James Tursa il 19 Ott 2016
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.

Accedi per commentare.

Risposta accettata

James Tursa
James Tursa il 19 Ott 2016
Modificato: James Tursa il 19 Ott 2016
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.

Più risposte (0)

Categorie

Scopri di più su Testing Frameworks in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by