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

15 views (last 30 days)
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.

Accepted Answer

Yongjian Feng
Yongjian Feng on 24 Jan 2022
Try this:
sprintf("\\Mann_Turb\\Seed_%.0f\\class4_10_seed%.0f\\class4_10_seed%.0f_v.bin", 600, 600, 600)

More Answers (1)

Steven Lord
Steven Lord on 24 Jan 2022
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.

Categories

Find more on Search Path in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!