How to force Matlab to read files in a folder serially?

前端 未结 4 2074
独厮守ぢ
独厮守ぢ 2021-01-23 22:33

I have files in a folder that are numbered from writer_1 to writer_20. I wrote a code to read all the files and store them in cells. But the problem is

4条回答
  •  长情又很酷
    2021-01-23 22:48

    Stealing a bit from DavidS and with the assumption that your folders all are of the form "writer_XX" with XX being digits.

    folders = dir([pwd '\temp']);
    folders(ismember( {folders.name}, {'.', '..'}) ) = [];
    
    % extract numbers from cell array
    foldersNumCell = regexp({folders.name}, '\d*', 'match');
    
    % convert from cell array of strings to double
    foldersNumber = str2double(foldersNumCell);
    
    % get sort order
    [garbage,sortI] = sort(foldersNumber);
    
    % rearrange the structure
    folders = folders(sortI);
    

    The advantage of this is that it avoids a for loop. In reality it only makes a difference though if you have tens of thousands for folders. (I created 50,000 folders labeled 'writer_1' to 'writer_50000'. The difference in execution time was about 1.2 seconds.

提交回复
热议问题