Error in SOR function.

5 次查看(过去 30 天)
I'm trying to create a function that performs the SOR method. Here is the code I have and the test program. When I ran the test program. There is an error " Error using - Matrix dimensions must agree. " What does it mean?
function[x]=SOR(A,b,x0,omega,tol,maxn)
k=1;
x=x0;
w=omega;
%x0 is the initial guess.
%omega is the relaxation parameter, typically larger than 1.
%tol is the tolerance for the stopping. Use the relative error.
%maxn is the maximum number of iterations allowed.
D=diag(diag(A));
L= tril(-A,-1);
U=triu(-A,1);
Tw=inv(D-w*L)*((1-w)*D+w*U);
cw=w*inv(D-w*L)*b;
while k<=maxn
x(:,k+1)=Tw*x(:,k)+cw;
if norm(x(:,k+1)-x(:,k))< tol
disp('x= ');
disp(x(:,k+1));
break
end
k=k+1;
end
end
% test program
clear
A = [3 -1 1; -1 3 -1; 1 -1 3];
b = [-1; 7; -7];
omega = 1.25;
x0 = [0; 0; 0];
tol = 1e-5;
maxn = 4;
x = SOR(A,b,x0,omega,tol,maxn);
xe=[0.942803389915179
2.00072895774848
-1.97233753473860];
error_1 = norm(x-xe,inf)
  1 个评论
John D'Errico
John D'Errico 2017-4-19
Why does it seem absurd that you are using SOR to solve a problem, when in your SOR code, you use the INV function for a major part of the computation?
Using a matrix inverse INSIDE a SOR tool that is itself a way to solve a linear system of equations is just silly. It is even more silly, since you can do that computation with a simple substitution loop.
Finally, it seems even more absurd that you are using inv TWICE, inverting the same lower triangular matrix.

请先登录,再进行评论。

采纳的回答

Sam McDonald
Sam McDonald 2017-4-19
I am able to execute the code you provided with no errors.
You may have another function called "SOR" on your MATLAB path that could be shadowing this "SOR" function you are intending to use. Check this by executing:
which -all SOR
I only have one listed, which is the one you provided here. MATLAB will use the function that is highest on the MATLAB path.
In general, the error "Matrix dimensions must agree" is thrown if an operation requires the dimensions of two variables to agree. A simple example is:
>> [1:3]*ones(4)
Error using * Inner matrix dimensions must agree.
The exact reason for the error depends on what operation you are performing. Look at what line of code the error is referencing and debug your code from there to understand what is happening.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by