歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Matlab對文件夾的層次遍歷和深度遍歷

Matlab對文件夾的層次遍歷和深度遍歷

日期:2017/3/1 9:33:27   编辑:Linux編程

最近做一個項目,由於數據分別放在不同的文件夾中,對大量數據文件“打開->復制->粘貼”,覺得很費事,於是就寫了對基於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 http://www.linuxidc.com/Linux/2014-09/106242.htm

Matlab與C/C++聯合編程之從Matlab調用C/C++代碼 http://www.linuxidc.com/Linux/2012-08/68148.htm

二分類SVM方法Matlab實現 http://www.linuxidc.com/Linux/2013-05/84050.htm

Matlab中的取整函數fix, floor, ceil與round http://www.linuxidc.com/Linux/2013-10/91161.htm

Matlab編譯cuda的.cu文件 http://www.linuxidc.com/Linux/2014-04/100675.htm

Linux Matlab服務器進一步改造成Application Server(應用程序服務器) http://www.linuxidc.com/Linux/2014-09/106340.htm

Copyright © Linux教程網 All Rights Reserved