fprintf and arrays of varying length

조회 수: 16 (최근 30일)
Keith Holmlund
Keith Holmlund 2018년 6월 19일
댓글: Star Strider 2025년 5월 2일
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)

댓글을 달려면 로그인하십시오.

채택된 답변

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
  댓글 수: 2
DanielFromIllinois
DanielFromIllinois 2025년 5월 2일
This should be the accepted answer.
Star Strider
Star Strider 2025년 5월 2일
@DanielFromIllinois — Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

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 '

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by