Matlab对文件夹的层次遍历和深度遍历

         最近做一个项目,由于数据分别放在不同的文件夹中,对大量数据文件“打开->复制->粘贴”,觉得很费事,于是就写了对基于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)


 

 

没有更多推荐了,返回首页