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

前端 未结 4 2069
独厮守ぢ
独厮守ぢ 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:52

    Approach #1

    %// From your code
    folders = dir(Path_training);
    folders(ismember( {folders.name}, {'.', '..'}) ) = []
    
    %// Convert folders struct to a cell array with all of the data from dir
    folders_cellarr = struct2cell(folders)
    
    %// Get filenames
    fn = folders_cellarr(1,:)
    
    %// Get numeral part and sorted indices
    num=str2double(cellfun(@(x) strjoin(regexp(x,['\d'],'match'),''), fn(:),'uni',0))
    [~,ind] = sort(num)
    
    %// Re-arrange folders based on the sorted indices
    folders = folders(ind)
    

    Approach #2

    If you would like to avoid struct2cell, here's an alternative approach -

    %// Get filenames
    fn = cellstr(ls(Path_training))
    fn(ismember(fn,{'.', '..'}))=[]
    
    %// Get numeral part and sorted indices
    num=str2double(cellfun(@(x) strjoin(regexp(x,['\d'],'match'),''), fn(:),'uni',0))
    [~,ind] = sort(num)
    
    %// List directory and re-arrange the elements based on the sorted indices
    folders = dir(Path_training);
    folders(ismember( {folders.name}, {'.', '..'}) ) = []
    folders = folders(ind)
    

    Please note that strjoin is a recent addition to MATLAB Toolbox. So, if you are on an older version of MATLAB, here's the source code link from MATLAB File-exchange.

提交回复
热议问题