Search code examples
matlabfor-loopfilenamesfile-extension

embed a number and extension in a variable file name


I want to save data to files that have consecutive numbers in these file names within a for-loop.

first I have a function "SetConfeguration.m" in which I specifie the input directory and the file name as fields in a structure as below

StrConf.InputDirectory = 'C:/ElastixMatlab/elx_input';
StrConf.ParameterFilename = 'parameter.%d.txt';

the structure "StrConf" will be used as a parameter in the main function as below

ParameterFilename = fullfile(Conf.InputDirectory, Conf.ParameterFilename);
for Cpt = 1:NbParameterFiles
   TmpParameterFilename = sprintf(ParameterFilename, Cpt - 1);
   disp('ParameterFilename: '); disp(ParameterFilename);
end

I have the following error:

Warning: Invalid escape sequence appears in format string. See help sprintf for
valid escape sequences. 
> In elxElastix at 153
  In elxExampleStreet at 93

ParameterFilename : 
C:\ElastixMatlab\elx_input\parameter.%d.txt

TmpParameterFilename : 
C:

Solution

  • You need to use sprintf before fullfile. The problem is that fullfile is normalizing your path separator from / used in your code, to \ which is the standard on Windows. But \ is also used for escape sequences which sprintf recognizes.

    This will work better:

    for Cpt = 1:NbParameterFiles
       TmpParameterFilename = fullfile(Conf.InputDirectory, ...
                                       sprintf(StrConf.ParameterFilename, Cpt - 1));
       disp('ParameterFilename: '); TmpParameterFilename;
    end