I can not find the error in this Gauss Seidal equation.
1 回表示 (過去 30 日間)
古いコメントを表示
%
function x1 = GaussSeidal(a,b,x0,tol)
N=100000;
k=1;
x=x0;
while(k<N)
n = length(b);
for j = 1 : n
x(j)=(b(j)-a(j,1:j-1).*x(1:j-1)-a(j,j+1:n)*x0(j+1:n))/a(j,j);
end
x1=x';
error=x1-x0;
if norm(error)< tol
disp('succefful');
break
end
k=k+1;
x0=x1;
end
disp(' The number of iteration is');disp(k)
tic;
gs_time=toc;
disp(gs_time);
end
end
%%Example
a=[5 -2 3;-3 9 1;2 -1 -7];b=[-1 2 3]';x0=[0 0 0]';tol=0.0001;
0 件のコメント
回答 (1 件)
Walter Roberson
2018 年 2 月 26 日
You have one too many end statements in your function.
In the line
x(j)=(b(j)-a(j,1:j-1)*x(1:j-1)-a(j,j+1:n)*x0(j+1:n))/a(j,j);
when j = 1, a(j,j+1:n) is a 1 x 2 vector, and x0(j+1:n) is a 1 x 2 vector. You have the * operator between two 1 x 2 vectors. The * operator is algebraic matrix multiplication, which requires that for an M x N array "*" a P x Q array, that N and P are the same -- M x N * N x Q giving an M x Q result. 1 x 2 * 1 * 2 does not follow that rule and so is an error. Possibly you want the .* operator instead of * but possibly not.
You also have the problem in that line a(j,1:j-1) is empty, which would make the result of a(j,1:j-1)*x(1:j-1) empty as well. An empty array minus something is empty, so you are down to (b(j) - empty)/a(j,j) but a scalar minus empty is empty too, so you are now down to empty / a(j,j) which will be empty as well, leaving you with x(1) = empty . Which is a problem: you cannot store a 0 x 0 array into a slot that expects 1 value.
5 件のコメント
Walter Roberson
2018 年 2 月 26 日
It does not matter that a*x0 produces a value. The a*x part is producing empty, and empty minus a value is either empty or an error.
Looks like I need to be more explicit for you:
Your problem is that your code needs to calculate based upon the content of the previous columns, which is a problem when you start your calculation from column 1 because there are no previous columns. So do not start from column 1.
参考
カテゴリ
Help Center および File Exchange で Numerical Integration and Differential Equations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!