Matlab對資料夾的層次遍歷和深度遍歷

guoxiaojie_415發表於2014-03-16

         最近做一個專案,由於資料分別放在不同的資料夾中,對大量資料檔案“開啟->複製->貼上”,覺得很費事,於是就寫了對基於Matlab的資料夾遍歷。文價夾遍歷有兩種方式,即層次遍歷和深度遍歷。個人比較傾向用層次遍歷的方法,因為深度遍歷要用到遞迴,當檔案目錄比較深的時候可能會出現棧溢位的現象(當然這只是個極端的情況),而且必須要做成一個函式,若需要記錄每個檔案的路徑,就比較麻煩!而層次遍歷思路相對簡單,易於理解,廢話不多說,直接貼上程式碼:

        【由於之前版本中有一些錯誤,現在修改過來了,並且給出了函式的呼叫Demo,歡迎大家一起交流學習

1、基於matlab的深度優先遍歷:

%   Input:
%    strPath: the directory of the file   
%    mFiles:  save the directory of the files
%    iTotalCount: the count of the walked files
%   Ouput:
%    mResFiles: the full directory of every file   
%    iTCount:   the total file count in the directory which your hava input


function [ mResFiles, iTCount ] = DeepTravel( strPath, mFiles, iTotalCount )
    iTmpCount = iTotalCount;
    path=strPath;
    Files = dir(fullfile( path,'*.*'));
    LengthFiles = length(Files);
    if LengthFiles <= 2
        mResFiles = mFiles;
        iTCount = iTmpCount;
        return;
    end


    for iCount=2:LengthFiles
        if Files(iCount).isdir==1  
            if Files(iCount).name ~='.'  
                filePath = [strPath  Files(iCount).name '/'];  
                [mFiles, iTmpCount] = DeepTravel( filePath, mFiles, iTmpCount);
            end  
        else  
            iTmpCount = iTmpCount + 1;
            filePath = [strPath  Files(iCount).name]; 
            mFiles{iTmpCount} = filePath;
        end 
    end
    mResFiles = mFiles;
    iTCount = iTmpCount;
end

2、基於Matlab的層次遍歷(廣度優先遍歷):

function [ mFiles ] = RangTraversal( strPath )
    %定義兩陣列,分別儲存檔案和路徑
    mFiles = cell(0,0);
    mPath  = cell(0,0);
    
    mPath{1}=strPath;
    [r,c] = size(mPath);
    while c ~= 0
        strPath = mPath{1};
        Files = dir(fullfile( strPath,'*.*'));
        LengthFiles = length(Files);
        if LengthFiles == 0
            break;
        end
        mPath(1)=[];
        iCount = 1;
        while LengthFiles>0
            if Files(iCount).isdir==1
                if Files(iCount).name ~='.'
                    filePath = [strPath  Files(iCount).name '/'];
                    [r,c] = size(mPath);
                    mPath{c+1}= filePath;
                end
            else
                filePath = [strPath  Files(iCount).name];
                [row,col] = size(mFiles);
                mFiles{col+1}=filePath;
            end

            LengthFiles = LengthFiles-1;
            iCount = iCount+1;
        end
        [r,c] = size(mPath);
    end

    mFiles = mFiles';
end

3、呼叫Demo:

clc
clear
close all

%% The directory of your files
str = 'C:/test/';

%% The use of depth-first walk
mFiles = [];
[mFiles, iFilesCount] = DeepTravel(str,mFiles,0)
mFiles = mFiles';

%% The use of breadth first walk
mFiles2 = RangTraversal(str)


 

 

相關文章