设为首页 加入收藏

TOP

Matlab对文件夹的层次遍历和深度遍历
2015-02-13 18:23:27 来源: 作者: 【 】 浏览:133
Tags: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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Python open() 函数 文件处理 下一篇如何定制对象中特定字段的JSON输..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: