我花了最后五个小时试图理解为什么这段代码陷入了无限循环。我发誓,我按照我在网上和其他地方的说明完全按照。感觉就像我尝试的一切都不起作用,我不知道为什么。
function [ K ] = linearSolve( a, b )
%Solves a system of equations. a = matrix of equations ; b = matrix
%of solutions
clear all
clc
%Example Matrices
a = [2,1,3;-2,-3,1;-3,4,-1];
b = [1,0,3];
%Defining initial & user values...
allowedError = input('Enter your max allowed error before stopping, in %: ');
X = input('Enter your inital guess matrix X: ');
dims = size(a);
iterations = 1;
maxiter = input('Maximum iterations: ');
error = allowedError + 100;
%Setting up K[i,j] matrix:
for r = 1:dims(1)
for c = 1:dims(2)
K(r,c) = -1*a(r,c)/a(r,r);
if r == c
K(r,c) = 0;
end
end
d(r) = b(r) / a(r,r);
end
%Performing Iteration...
while error > allowedError
iterations = iterations + 1;
prevGuess = X;
for j = 1:dims(1)
X(j) = K(j,:)*X(:) + d(j);
error(j) = abs(((X(j) - prevGuess(j))/X(j))*100);
end
if (allowedError >= error) | (iterations >= maxiter)
break
end
end
%Display Results
disp('The values of X are: ');
disp(X);
disp('------------------------------------');
disp('The error is: ');
disp(error);
end