Matlab file name with zero-padded numbers

The problem

['F',num2str(i), '_', num2str(j),'.mat']

evaluates to


and not to


as expected.

The reason for this is that i=01 is a double type assignment and i equals to 1 – there are no leading zeros for these types of variables.

A solution

a possible solution for the problem would be

for ii = 1:11
    for jj= 1:11
        filename = sprintf('F_%02d_%02d.mat', ii, jj );
        Func(Fi_j);   % run the function for each file  Fi_j  

Several comments:

  1. Note the use of sprintf to format the double ii and jj with leading zero using %02d.

  2. You can use the second argument of num2str to format its output, e.g.: num2str(ii,'%02d').

  3. It is a good practice to use string formatting tools when dealing with strings.

  4. It is a better practice in matlab not to use i and j as loop counters, since their default value in matlab is sqrt(-1).

Leave a Comment