I'm solving a system Ax=b with Jacobi. I got it to run through once, but now I need a driver to run 20 iterations of each, while printing the infinity norm of ||t-x^i|| ,where x^i is generated from an initial guess of x0, to a table each iteration.

조회 수: 2 (최근 30일)
function driver
A = [4 -1 -1 0;-1 4 0 -1;-1 0 4 -1;0 -1 -1 4]';
b = [10.5;-13;1;-1.5];
n = 4;
%% exact solution
t = [2;-3;.5;-1];
x0=[0; 0; 0; 0];
%% updated x vector for infinity norm
x=(1:n);
for i= 1:20
if i = 1
%% initiating jacobi with x0
x = x0;
else x=x(i);
end
Jacobi(A,b,x,n)
%% calculating the infinity norm each iteration
z=norm(t-x(i),inf);
end
end

답변 (1개)

Balaji
Balaji 2024년 5월 15일
Hello Austin,
I understand that you want to solve a system (Ax=b) using the Jacobi method and calculating the infinity norm of (|t-x^i|).
Here's a corrected version of your script with comments:
A = [4 -1 -1 0;-1 4 0 -1;-1 0 4 -1;0 -1 -1 4]';
b = [10.5;-13;1;-1.5];
n = 4;
%% exact solution
t = [2;-3;0.5;-1];
x0 = [0; 0; 0; 0];
%% Initialize x for infinity norm calculation
x = x0;
%% Print header for the table
fprintf('Iteration\tInfinity Norm\n');
for i = 1:20
x_new = Jacobi(A, b, x, n); % Get the new x using Jacobi method
z = norm(t - x_new, inf); % Calculating the infinity norm
% Print the current iteration and infinity norm
fprintf('%d\t\t\t%f\n', i, z);
x = x_new; % Update x for the next iteration
end
function x_new = Jacobi(A, b, x, n)
x_new = zeros(n, 1); % Initialize new x vector for the current iteration
for i = 1:n
sum = 0;
for j = 1:n
if j ~= i
sum = sum + A(i, j) * x(j);
end
end
x_new(i) = (b(i) - sum) / A(i, i);
end
end
This script now correctly performs 20 iterations of the Jacobi method to solve the system (Ax=b) and prints the infinity norm of (|t-x^i|) after each iteration.
Hope this helps,
Thanks,
Balaji

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by