New line after fprintf in a for/ while loop

조회 수: 10 (최근 30일)
Serbando Jauregui
Serbando Jauregui 2023년 8월 28일
답변: Image Analyst 2023년 8월 28일
I have an if else statement in a for loop that displays a relative error if the iterations is between a certain number. The only problem is that i can not seem to add a \n at the end of the fprint if because it ends up freaking out. Is there a way to add a linespace for this fprintf within an if else statement without having this error? Thanks
  댓글 수: 1
Les Beckham
Les Beckham 2023년 8월 28일
If you provide your code (or a simplified version of it that still exhibits the problem) along with any data needed to allow it to run successfully, you will be much more likely to get an answer.
What do you mean by "it ends up freaking out"? Is there an error message? If so, cut and paste the entire error message (all of the red text in the command window) in a comment (or edit your question).

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

채택된 답변

David Hill
David Hill 2023년 8월 28일
a=randi(100,1,100);
for k=1:100
formatSpec = 'a is %2g\n';
if a(k)>90
fprintf(formatSpec,a(k));
end
end
a is 96 a is 95 a is 92 a is 92 a is 99 a is 91 a is 99 a is 94

추가 답변 (2개)

dpb
dpb 2023년 8월 28일
편집: dpb 2023년 8월 28일
Certainly the if...else...end clause itself has absolutely nothing to do with handling a newline in an fprint formatting string.
To illustrate proper syntax we can make up just a dummy test...
V=rand(10,1)
V = 10×1
0.5726 0.9293 0.8324 0.9603 0.8983 0.5216 0.7049 0.5235 0.5645 0.6107
for i=2:numel(V)
if V(i)-V(i-1)>0
fprintf('Iteration: %d GT 0\n',i)
else
fprintf('Iteration: %d LE 0\n',i)
end
end
Iteration: 2 GT 0
Iteration: 3 LE 0
Iteration: 4 GT 0
Iteration: 5 LE 0 Iteration: 6 LE 0
Iteration: 7 GT 0
Iteration: 8 LE 0
Iteration: 9 GT 0 Iteration: 10 GT 0

Image Analyst
Image Analyst 2023년 8월 28일
Let's say you loop over val1 to val2, and you want to only enter the loop if val1 is more than 5 and val2 is less than 80. One way to do it would be to check in advance and never enter the for loop:
if (val1 <= 5) || (val2 > 80)
warningMessage = sprintf('For loop iterators out of range.\nValid range is 5-80.\nNow it is trying %d to %d', val1, val2)
uiwait(errordlg(warningMessage))
return; % Quit routine.
end
for k = val1 : val2
% code to run if the values are in range.
end
Another way to do it is to check inside the loop and break out
for k = 1 : 999
if (k <= 5) || (k > 80)
warningMessage = sprintf('For loop iterators out of range.\nValid range is 5-80.\nNow it is trying %d.', k)
uiwait(errordlg(warningMessage))
break; % Quit for loop, or use continue to continue with the next k.
end
end

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by