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


最近做一个项目,由于数据分别放在不同的文件夹中,对大量数据文件“打开->复制->粘贴”,觉得很费事,于是就写了对基于Matlab的文件夹遍历。文价夹遍历有两种方式,即层次遍历和深度遍历。个人比较倾向用层次遍历的方法,因为深度遍历要用到递归,当文件目录比较深的时候可能会出现栈溢出的现象(当然这只是个极端的情况),而且必须要做成一个函数,若需要记录每个文件的路径,就比较麻烦!而层次遍历思路相对简单,易于理解。废话不多说,直接贴上代码:

1、基于matlab的深度优先遍历:

function RenameFile( strPath )
    path=strPath;
    Files = dir(fullfile( path,'*.*'));
    LengthFiles = length(Files);
    for iCount = 1:LengthFiles    % 判断是否是文件夹   
        name = Files(iCount).name;   
        if name=='.'       
            continue;   
        end
        s = [path  name '/'];        %遍历文件 
        Folders = dir(fullfile( s,'*.*'));   
        Length= length(Folders);       
        for iCount = 1:Length;         
            if strcmp(Folders(iCount).name, '.') | ...
              strcmp(Folders(iCount).name, '..')
                continue;
            end
            %对文件进行操作
            Folders(iCount).name
        end
    end
end

2、基于Matlab的层次遍历(广度优先遍历):

 %定义两数组,分别保存文件和路径
mFiles = cell(0,0);
mPath  = cell(0,0);

mPath{1}='./';
[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

Ubuntu Server上安装Matlab

Matlab与C/C++联合编程之从Matlab调用C/C++代码

二分类SVM方法Matlab实现

Matlab中的取整函数fix, floor, ceil与round

Matlab编译cuda的.cu文件

Linux Matlab服务器进一步改造成Application Server(应用程序服务器)

本文永久更新链接地址:

相关内容