How can I force a for loop to finish all iterations without using 'end'? I want my for loop to finish before moving onto line 11 otherwise some values will be missing.
조회 수: 1 (최근 30일)
이전 댓글 표시
h = 0.01; %step size
A = 8000/11; %constant value
T(1)=80; %initial temperature
x(1)=0; % length along rod, 0cm to 4cm
prompt = ('Guess initial Z value');
Z(1) = input(prompt); % initial Z value (guessed) used to obtain T values
for i=2:5; % loop that should produce 5 T values and 5 Z values corresponding to different points along the rod
x(i) = x(i-1)+h;
T(i) = T(i-1) + h*Z(i-1)
Z(i) = Z(i-1) + h*(A*(T(i-1)-20));
if (T(5)-(20-(55/20)*Z(5))) < 0.1 % if initial guess is correct then a plot should be produced
plot(x,T)
break
else % if initial guess is incorrect then a new guess must generated using equation below
Z1=Z(1)
Z(1) = Z1 - Z(5) % loop needs to continue until plot is produced
end
end
% My code does not complete iterations 2:5 to get all values including T(5) and Z(5), instead it completes one iteration and moves onto the if statement which results in an error because T(5) AND Z(5) are missing.
% Is there a way to force the loop to finish completely each time before moving onto the IF statement?
댓글 수: 7
Image Analyst
2019년 1월 6일
The first time through, how is there any Z at all in index 5? Since you only input 1 values when you try to access Z(5) in the if statement, it should throw an error because there is no Z(5) yet. What are you entering for Z?
I think you should use clearvars
>> clearvars
because I think your code maybe using old values of Z, with higher indexes, that are still hanging around.
Tell us what you are entering at the prompt for Z(1). I assume it's just one number, but maybe not.
답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!