How to convert the for loop to a while loop?
조회 수: 3 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
MG
2021년 3월 30일
편집: MG
2021년 3월 30일
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).
댓글 수: 3
MG
2021년 3월 31일
편집: MG
2021년 4월 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.
- 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).
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!