MATLAB: Fprintf and arrays of varying length

fprintfMATLABsprintf

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

Best Answer

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 '
Related Question