A Sprintf For Loop Breakdown
    조회 수: 3 (최근 30일)
  
       이전 댓글 표시
    
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 
댓글 수: 0
채택된 답변
  Stephen23
      
      
 2020년 4월 20일
        
      편집: Stephen23
      
      
 2020년 4월 20일
  
      "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
추가 답변 (0개)
참고 항목
카테고리
				Help Center 및 File Exchange에서 Convert Image Type에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

