How to convert the for loop to a while loop?

2 views (last 30 days)
Avinash Gupta on 30 Mar 2021
Edited: MG on 1 Apr 2021
A = [7 3 2 1; 2 9 4 5; 1 3 13 4; 4 5 8 14 ]; % A is diagonally dominant
b = [1;2;3;4];
x = zeros(4,1);
x_new = zeros(4,1);
% Gauss Seidel using for loop
n = 4;
for iter = 1:25
for i = 1:n
num = b(i)-A(i,1:i-1)*x_new(1:i-1) - A(i,i+1:n)*x(i+1:n);
x_new(i) = num/A(i,i);
x = x_new;
end
disp(['At iteration = ',num2str(iter), ' x = ', num2str(x_new')]);
end
% The for loop works but the while loop doesn't
%% This is what I have done in the while loop.
% Gauss seidel using while loop
n = 4;
error = 0;
iter = 0;
while error >=1e-6
for i = 1:n
x_new(i) = (b(i)-A(i,1:i-1)*x_new(1:i-1)- A(i,i+1:n)*x(i+1:n))/A(i,i);
x = x_new;
error = abs(x-x_new);
end
iter = iter+1;
disp(['At iteration = ',num2str(iter), ' x = ', num2str(x_new')]);
end

MG on 30 Mar 2021
Edited: MG on 30 Mar 2021
Hi Avinash,
I modified your code into something I believe is what you might want:
A = [7 3 2 1; 2 9 4 5; 1 3 13 4; 4 5 8 14 ]; % A is diagonally dominant
b = [1;2;3;4];
x = zeros(4,1);
x_new = zeros(4,1); %<---- modified
% Gauss seidel using while loop
n = 4;
error = ones(4,1); %<---- modified
iter = 0;
while prod( error >= 1e-6*ones(4,1) ) %<---- modified
for i = 1:n
x_new(i) = (b(i)-A(i,1:i-1)*x_new(1:i-1)- A(i,i+1:n)*x(i+1:n))/A(i,i);
error(i) = abs(x(i)-x_new(i)); %<---- modified
x(i) = x_new(i); %<---- modified to be after error
end
iter = iter+1;
disp(['At iteration = ',num2str(iter), ' x = ', num2str(x_new')]);
end
I then just notice that you have in your code this code sequence
A(i,1:i-1)*x_new(1:i-1)
and I don't know if that does what you expect, beceuse with i =1 then A(1,1:0) *x_new(1:0) is a multiplication of two empty matrices (that probably returns 0).
MG on 31 Mar 2021
Edited: MG on 1 Apr 2021
1. You can use your original 'error >= 1e-6', it should do the same thing. I only did it to more explicitely show that it checks individually each of the elements in your 4 component 'error' array. If any is false, the loop stops. Replace 'prod' with 'any' if you instead want that every error(i) < 1e-6 before the while-loop ends.
2. Fine, as long as it does what you intend (in practice that is a a multiplication of two empty arrows that here return 0, but I'm not really sure why it returns 0 and not an empty matrix).

Categories

Find more on Matrix Indexing in Help Center and File Exchange

R2021a

Community Treasure Hunt

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

Start Hunting!