Help me to fix it because the error said Attempted to access xnew(2); index out of bounds because numel(xnew)=1. Error in jacobi (line 22) err = norm(xnew(i)-x(i),Inf)/norm(xnew(i),Inf);
    4 views (last 30 days)
  
       Show older comments
    
a = [1, 0, -1; -1/2, 1, -1/4;1, -1/2, 1];
b = [0.2; -1.425; 2];
n = length(b);
x = zeros(n,1);
xnew = zeros(n,1);
x(:) = 0;
iterlimit = 3;
tol = 0.001;
for iteration = 1 : iterlimit
    convergence = true;
    for i=1 : n %loop of equtions
        sum = 0;
        for j = 1: n % loop of summation
            if j~= i
                sum = sum + a(i,j) * x(j)
            end;
        end;
        xnew = -(1/a(i,i)) * (sum - b(i));
          err = norm(xnew(i)-x(i),Inf)/norm(xnew(i),Inf);
          if err <0 tol
              convergence = false;
          end;  
      end;
      if convergence
          break
      end
      x = xnew;
  end;
  disp('iteration: ')
  iter
  disp('solution: ')
  xnew
0 Comments
Answers (1)
  Torsten
      
      
 on 29 Oct 2018
        In the line
xnew = -(1/a(i,i)) * (sum - b(i));
you reset xnew from a (3x1) vector to a scalar. That's the reason why for i=2 the element xnew(2) no longer exists.
Best wishes
Torsten.
0 Comments
See Also
Categories
				Find more on Loops and Conditional Statements in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!