A Sprintf For Loop Breakdown

4 views (last 30 days)
Matpar
Matpar on 20 Apr 2020
Edited: Stephen23 on 20 Apr 2020
Hi all I am seeking assitance in understanding the following code and the sprintf statement!
I googled and youtubed this but still I don't get this can someone assist me, please?
I don't understand the sprintf what does the %3.3d.jpg do?
So far what I understanding is that this statement prints a minimum of 3 files but what does the %3.3d.jpg????!!!!??
Lastly the numFramesWritten1 = numFramesWritten1 + 1; What does the 1 do?!!!?? add 1 to every frame that is being written???
I don't get it!!!!???!!
Please help!
My code:
% Deploying For Loop To Traverse & Process From Frame '1' To 'last' Frame
for t = 1 : numFrames1
currFrame1 = read(filename1, t); % Reading Individual Frames
opBaseFileName1 = sprintf('%3.3d.jpg', t);
opFullFileName1 = fullfile(Violence3, opBaseFileName1);
imwrite(currFrame1, opFullFileName1, 'jpg'); % Saving Frames As 'jpg' Files
Indicating Current Progress Of Files/Frames Written
%Writing the minimum digits to be printed using 4decimal notations signed
progIndication1 = sprintf('Writing Frame %4d of %d.', t, numFrames1);
disp(progIndication1);
numFramesWritten1 = numFramesWritten1 + 1;
end

Accepted Answer

Stephen23
Stephen23 on 20 Apr 2020
Edited: Stephen23 on 20 Apr 2020
"I don't understand the sprintf what does the %3.3d.jpg do"
It is confusing because that formatting string uses undocumented behavior of sprintf.
Do NOT learn from that format string! (except perhaps how NOT to write format strings).
A naive interpretation of that format string might be
'%3.3d.jpg'
% start of formatting operator
3 field width (min three characters)
.3 precision (makes no sense with 'd' conversion type or an integer value)
d conversion type (signed integer)
.jpg literal string '.jpg'
So we would expect this to print a string with minimum characters, but obviously requesting three fractional digits from an integer is absolute nonsense, and so the string is actually parsed like this:
'%3.3d.jpg'
% start of formatting operator
3 field width (min three characters)
.3 number of digits including leading zeros (not documented!)
d conversion type (signed integer)
.jpg literal string '.jpg'
You can see this undocumented behavior with a few simple examples, e.g. a fieldwidth of 5:
>> sprintf('X%5.3d.jpg',7) % added 'X' to show the leading spaces
ans =
X 007.jpg
The proper, documented way to generate a string with leading zeros is like this:
>> sprintf('X%03d.jpg',7) % added 'X' to show leading spaces (i.e. none)
ans =
X007.jpg
  1 Comment
Matpar
Matpar on 20 Apr 2020
Thank you so much, Understood! this was cofusing the hell out of me!!
I got it thanx!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!