Trying to run Gauss Siedel method, I have no idea where I'm going wrong in this code. I get an error of "Index exceeds matrix dimensions" Not sure how? Just need this to run Thanks

1 次查看(过去 30 天)
% Solve system from HW using Gauss Seidel
% System of Equations Simplified Below
% 2x1-3x2=-160 ---> x1=(3x2-160)/2
% x1+2x2-3x3 -----> x2=(3x3-x1+40)/2
% 2x3-x2=80 ------> x3=(x2+80)/2
clear;clc;
i=1;
x2(i)=0;x3(i)=0;
error_x1(i)=9999;
while error_x1(i) >= .01;
x1(i+1)=(3*x2(i)-160+0*x3(i))/2;
x2(i+1)=(3*x3(i)-x1(i+1)+40)/2;
x3(i+1)=(x2(i+1)+80+0*x1(i+1))/2;
errorx1(i+1)=abs((x1(i+1)-x1(i))/x1(i+1))*100;
errorx2(i+1)=abs((x2(i+1)-x2(i))/x2(i+1))*100;
errorx3(i+1)=abs((x3(i+1)-x3(i))/x3(i+1))*100;
i=i+1;
end
disp(' x1 error(%)');
disp([x1',error_x1']);
disp(' x2 error(%)');
disp([x2',error_x2']);
disp(' x3 error(%)');
disp([x3',error_x3']);

回答(2 个)

Marc Jakobi
Marc Jakobi 2016-10-5
You have to pre-initialize x1, x2, x3, errorx1, errorx2 and errorx3. The index exceeds the matrix dimensions, because you index x1(i+1), which is x1(2) in the first iteration of your loop. Since x1 is initialized with a length of 1, the index 2 exceeds the dimension 1.
One solution would be
clear;clc;
i=1;
errorx1=9999;
errorx2 = 9999;
errorx3 = 9999;
x1 = 0;
x2 = 0;
x3 = 0;
while errorx1(i) >= .01
x1 = [x1; (3*x2(i)-160+0*x3(i))/2];
x2 = [x2; (3*x3(i)-x1(i+1)+40)/2];
x3 = [x3; (x2(i+1)+80+0*x1(i+1))/2];
errorx1 = [errorx1; abs((x1(i+1)-x1(i))/x1(i+1))*100];
errorx2 = [errorx2; abs((x2(i+1)-x2(i))/x2(i+1))*100];
errorx3 = [errorx3; abs((x3(i+1)-x3(i))/x3(i+1))*100];
i=i+1;
end
disp(' x1 error(%)');
disp([x1',errorx1']);
disp(' x2 error(%)');
disp([x2',errorx2']);
disp(' x3 error(%)');
disp([x3',errorx3']);

Walter Roberson
Walter Roberson 2016-10-5
You initialized
error_x1(i)=9999;
and you have
while error_x1(i) >= .01;
which is consistent. But then you have
errorx1(i+1)=abs((x1(i+1)-x1(i))/x1(i+1))*100;
which is assigning into a different variable, one that does not have the underscore.

类别

Help CenterFile Exchange 中查找有关 Formula Manipulation and Simplification 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by