fprintf not displaying in loop

ive tried for and while loops for this. if its outside of the loop, it prints fine, but not inside, can someone help me understand why it doesnt work
clear
clc
Year = [2019 2020 2021 2023 2024 2026];
Month = [ 7 12 12 4 4 8];
Day = [ 2 14 4 20 8 12];
budget = input('what is your required budget? $');
saveRate = input('how much will you save per day? $');
savingsI = input('what is your initial savings? $');
dateI = 1 + 30.44 * 0 + 365.2425 * 2017;
dateF = Day + 30.44 .* Month + 365.2425 .* (Year - 1);
daysT = dateF - dateI;
savings = daysT .* saveRate + savingsI;
fprintf('with a required budget of $%d, you can attend the following total solar eclipse(s)\n',budget)
while savings > budget
fprintf('A total solar eclipse that occurs at %4.0f days with a savings balance of $%4.0f\n',[daysT;savings])
end

답변 (1개)

Geoff Hayes
Geoff Hayes 2019년 4월 26일

0 개 추천

hubert - you may need to clarify what you mean by if its outside of the loop, it prints fine, but not inside. If I run your code, with random inputs such that your while condition is always satisfied, then I get "stuck" in the loop with the same line or lines being printed out until I cancel the program. Look closely at
while savings > budget
fprintf('A total solar eclipse that occurs at %4.0f days with a savings balance of $%4.0f\n',[daysT;savings])
end
One problem is that budget is a scalar and that savings could be an array. What is your intention with the comparison of
savings > budget
? Should all elements in the savings array be compared to budget? Since there is no change to either savings or budget in the body of the loop, then you will never exit the looo until you cancel the running program.
Perhaps what you intend is something like
for k = 1:length(savings)
if savings(k) > budget
fprintf('A total solar eclipse that occurs at %4.0f days with a savings balance of $%4.0f\n',daysT(k), savings(k));
end
end
Or not?

댓글 수: 1

Amin Kassab-Bachi
Amin Kassab-Bachi 2021년 8월 18일
편집: Amin Kassab-Bachi 2021년 8월 18일
I think I'm having a similar issue here. Basically, I'm running a for loop, and at the end of each iteration I want matlab to print the number of the finished iteration. but matlab holds all printing (looks as if it's frozen) untill I cancel the loop or it's done, then suddenly all of the statements are printed. So, it's not that fprintf is not working, but the GUI just gets stuck while MATLAB is working on something large. I noticed similar issues in Python as well.
The solution is to add a small pause at the end of the loop, half a second should be sufficient.

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

카테고리

도움말 센터File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

질문:

N/A
2019년 4월 26일

편집:

2021년 8월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by