Loop does not work

조회 수: 9 (최근 30일)
Mehmet
Mehmet 2023년 12월 30일
댓글: Torsten 2023년 12월 31일
format long
tolerance = 10^-15;
y=0.1;
h=[y,y/2,y/4,y/8,y/16];
x=0;
I = (exp(x+h)-exp(x))./h;
z = length(h);
for n = 1:z-1 ;
while m < z-n
I(m) = (4/3) * I(m+1) - (1/3) * I(m);
m = m+1;
end
end
I
This is the code and i expected that the I matrix should go into the loop several times and as a result I should see 1x1 matrix but the loop stops after first iteration. What could be the problem?
  댓글 수: 3
Torsten
Torsten 2023년 12월 30일
편집: Torsten 2023년 12월 30일
Is this Richardson extrapolation ? Or what are you trying to do in your code ?
Shouldn't I be a lower triangular matrix in this case instead of a vector ?
Torsten
Torsten 2023년 12월 31일
If I is a matrix, then why do you work with it as a vector ?

댓글을 달려면 로그인하십시오.

채택된 답변

Hassaan
Hassaan 2023년 12월 30일
편집: Hassaan 2023년 12월 30일
You haven't initialized m before the loop starts, and you're using it as a loop index. This can lead to unexpected behavior or errors. Furthermore, your while loop condition m < z-n might not be behaving as expected, especially if m is not properly initialized and updated. Here's are some suggestions:
  1. Initialize m: Before entering the while loop, you should initialize m to a starting value. Typically, for MATLAB indexing, you would start with m = 1.
  2. Reset m in each iteration: You need to reset the value of m for each iteration of your n loop. If you don't reset it, m will eventually exceed z-n, and the inner loop won't run in subsequent iterations of the outer loop.
  3. Adjust the loop conditions: Ensure that the loop runs as many times as you expect and that the indices used inside the loop do not exceed the dimensions of your I array.
format long
tolerance = 10^-15;
y = 0.1;
h = [y, y/2, y/4, y/8, y/16];
x = 0;
I = (exp(x + h) - exp(x)) ./ h;
z = length(h);
for n = 1:(z-1)
m = 1; % Initialize m at the beginning of each n loop
while m <= (z - n) % Ensure m doesn't exceed the updated length of I
I(m) = (4/3) * I(m + 1) - (1/3) * I(m);
m = m + 1;
end
I = I(1:end-1); % After updating I, truncate the last element
end
disp(I)
1.000617319458443
------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
  댓글 수: 1
Mehmet
Mehmet 2023년 12월 30일
thank you for answering. but i couldn't understand that why the truncation of the matrix made it work?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by