Matlab file name with zero-padded numbers

醉酒当歌 提交于 2019-11-26 14:38:54

问题


I have 11x11 matrices and I saved them as .mat files from F01_01 to F11_11. I have to run a function Func on each file. Since it takes a long time, I want to write a script to run the function automatically:

for i=01:11  
    for j=01:11  
        filename=['F',num2str(i), '_', num2str(j),'.mat'];  
        load(filename);  
        Func(Fi_j);   % run the function for each file  Fi_j  
    end  
end  

But it doesn't work, Matlab cannot find the mat-files.
Could somebody please help ?


回答1:


The problem

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

evaluates to

F1_1.mat

and not to

F01_01.mat

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 );
        load(filename);  
        Func(Fi_j);   % run the function for each file  Fi_j  
     end  
end

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).




回答2:


Here is an alternate solution, note that the solution by @Shai is more easily expanded to multiple digits but this one requires less understanding of string formatting.

for i=1:11  
        for j=1:11  
            filename=['F',num2str(floor(i/10)),num2str(mod(i,10)) '_', num2str(floor(j/10)),num2str(mod(j,10)),'.mat'];  
            load(filename);  
            Func(Fi_j);   % run the function for each file  Fi_j  
       end  
end 



回答3:


The num2str can do zeropadding to fill the field. In the example below 4 is the desired field width+1.

num2str(1,'% 04.f')

Ans = 001



来源:https://stackoverflow.com/questions/14213442/matlab-file-name-with-zero-padded-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!