Issues with my jacobian method code

조회 수: 1 (최근 30일)
Kathy Lindquist
Kathy Lindquist 2016년 10월 9일
편집: Marc Jakobi 2016년 10월 9일
I've been messing around with my code for a while, but the x value it outputs never comes out correct.
function [x] = jacobi(A,b,x0,n_iter)
%A=[10 -1 2 0;-1 11 -1 3;0 3 -1 8; 2 -1 10 -1];
%x0=[1;1;1;1];
%b=[6 25 -11 15];
%n_iter=10;
n=length(x0);
x=zeros(size(x0));
for k=1:1:n_iter
for i=1:1:n
temp=0;
for j=1:1:n
temp=temp+A(i,j)*x(j);
end
temp=temp-A(i,i)*x0(i);
x(i)=(1/A(i,i))*(b(i)-temp);
end
x0=x;
end
disp(x)
I'm just unsure which line I have messed up.

채택된 답변

Marc Jakobi
Marc Jakobi 2016년 10월 9일
편집: Marc Jakobi 2016년 10월 9일
Just a small error in your code. Here's the correction:
function [x] = jacobi(A,b,x0,n_iter)
n=length(x0);
x = zeros(size(x0));
for k=1:n_iter
for i=1:n
temp=0;
for j=1:n
temp=temp+A(i,j)*x0(j); %you should use x0(j) here, not x(j)
end
temp=temp-A(i,i)*x0(i);
x(i)=(1/A(i,i))*(b(i)-temp);
end
x0=x;
end
disp(x)
end
However, you could also do it like this:
function [x] = jacobi(A,b,x0,n_iter)
n=length(x0);
x = zeros(size(x0));
for k=1:n_iter
for i=1:n
temp=0;
inds = [1:i-1, i+1:n];
temp = A(i,inds)*x0(inds);
x(i)=(1/A(i,i))*(b(i)-temp);
end
x0=x;
end
disp(x)
end

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by