How to have a variable format spec print length when using fprintf?
    10 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    AdamG2013468
      
 el 15 de Ag. de 2019
  
    
    
    
    
    Respondida: Jess Lovering
      
 el 15 de Ag. de 2019
            I am trying to print column header information to a .txt file using fprintf. I am importing the column header information from another file. The problem is that the imported column header information can be any character length, as defined by the user (e.g. could be 1 character long, could be 20). I would like to use the maximum header length to define how much space will be needed when printing the column headers/labels. The code in question is summarized below:
for i = 1:length(headerinformation)
    fprintf(fid,'%10s',headerinformation{i})
end
The default amount of space I am using is 10 (i.e. %10s), but this doesn't work well when the headers are > 10. At first i tried using the maximum header lenth variable to define the maximum header length, but this didn't work properly when using the fprintf format spec. I tried something similar to the following:
MaxHeaderLength = max(cell2mat(columnheaderlength));
for i = 1:length(headerinformation)
    fprintf(fid,'%(%i)s',headerinformation{i}, MaxHeaderLength) %parenthesis around %i added for explanation only, i know this wouldn't actually work
end
Any guidance would be appreciated.
0 comentarios
Respuesta aceptada
  Jess Lovering
      
 el 15 de Ag. de 2019
        Would this work for what you need?
MaxHeaderLength = max(cell2mat(columnheaderlength));
max_fmt_spec = ['%' num2str(MaxHeaderLength) 's'];
for i = 1:length(headerinformation)
    fprintf(fid,max_fmt_spec,MaxHeaderLength) 
end
0 comentarios
Más respuestas (0)
Ver también
Categorías
				Más información sobre Entering Commands en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

