Sprintf problems while trying to format a directory name followed by a string

조회 수: 13(최근 30일)
Dear all,
I am trying to write a directory name using the sprintf command. More specifically, the line I am working on is the following:
"Mann_Turb/Seed_600/class15_25_seed600/class15_25_seed600_u.bin" FileName_u - name of the file containing the u-component fluctuating wind (.bin),
where the part in bold and in parentheses is the path and the other is the string.
I want to change the number 600 in 3 other numbers using a for loop. However, I am having formatting issues for the command sprintf. What I am doing is the following:
sprintf(\Mann_Turb\Seed_ %.0f \class4_10_seed%.0f \class4_10_seed%.0f _v.bin" - FileName_u - name of the file containing the u-component fluctuating wind (.bin) ',seed(k));
However, the line does not appear in the output file I create. In case I use a simple phrase e.g 'The time is %.0f ', seed(k), the output changes according to the for loop.
Does anyone have a solution to this issue?
Thank you very much,
Ioannis Voultsos.

채택된 답변

Yongjian Feng
Yongjian Feng 2022년 1월 24일
Try this:
sprintf("\\Mann_Turb\\Seed_%.0f\\class4_10_seed%.0f\\class4_10_seed%.0f_v.bin", 600, 600, 600)

추가 답변(1개)

Steven Lord
Steven Lord 2022년 1월 24일
The backslashes and the characters following them are being treated as escape-character sequences. See the second line in the description of the formatSpec input argument on the documentation page for the sprintf function.
Instead of using sprintf I would use fullfile and string.
s = 600;
c = 15;
filename = fullfile("Mann_Turb", "Seed_" + s, "class" + c + "_25_seed_" + s + "_u.bin")
filename = "Mann_Turb/Seed_600/class15_25_seed_600_u.bin"
This will also avoid problems if you run this code on different platforms. The machinery that MATLAB Answers uses to publish code is Linux, so fullfile uses the appropriate file path separator.
computer
ans = 'GLNXA64'
filesep
ans = '/'
On Windows filesep would return '\' and that's what fullfile would use to separate its inputs.

Community Treasure Hunt

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

Start Hunting!

Translated by