fprintf and arrays of varying length

16 visualizaciones (últimos 30 días)
Keith Holmlund
Keith Holmlund el 19 de Jun. de 2018
Comentada: Star Strider el 2 de Mayo de 2025
I have a function where one of the inputs is an array, i.e A = [1 1 1 1] or A = [1 1 1 1 1 1 1]. I would like to use fprintf and/or sprintf to write the array to a text file. I know I can specify formatSpec to a specific length, like '%d %d %d %d' but if the array can vary in length, is there a way to make sure the formatSpec has the same number of %d as the amount of numbers in the array
  1 comentario
Stephen23
Stephen23 el 19 de Jun. de 2018
"is there a way to make sure the formatSpec has the same number of %d as the amount of numbers in the array"
fprintf(' %d',A)

Iniciar sesión para comentar.

Respuesta aceptada

Star Strider
Star Strider el 19 de Jun. de 2018
The fprintf (and sprintf) functions will do that by default:
A = [1 1 1 1 1];
fprintf('%2d', A)
fprintf('\n')
1 1 1 1 1
  2 comentarios
DanielFromIllinois
DanielFromIllinois el 2 de Mayo de 2025
This should be the accepted answer.
Star Strider
Star Strider el 2 de Mayo de 2025
@DanielFromIllinois — Thank you!

Iniciar sesión para comentar.

Más respuestas (1)

Ameer Hamza
Ameer Hamza el 19 de Jun. de 2018
Editada: Ameer Hamza el 19 de Jun. de 2018
A = [1 1 1 1 1];
repmat('%d ', 1, length(A))
ans =
'%d %d %d %d %d '
sprintf(repmat('%d ', 1, length(A)), A)
ans =
'1 1 1 1 1 '

Categorías

Más información sobre Operators and Elementary Operations en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by