fprintf and arrays of varying length

58 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2018-6-19
"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)

请先登录,再进行评论。

采纳的回答

Ameer Hamza
Ameer Hamza 2018-6-19
编辑:Ameer Hamza 2018-6-19
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 '

更多回答(1 个)

Star Strider
Star Strider 2018-6-19
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

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by