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 Center および File ExchangeTesting Frameworks についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by