MATLAB batch read folder name, file name, file data


1. Introduction

When we are studying some topics, we often encounter a large amount of data that needs to be processed. When there are a large number of data files, we need to read the data in the files in batches and convert them into matrices for calculation.
At present, the data I want to process is one month's data for a project, as shown in the following figure:
Insert picture description here
Here, first create a folder named 1st in the "D:/September/1st" directory, and generate 100 in the folder. A txt file.

new_folder= 'D:/9月/1日'; % new_folder 保存要创建的文件夹,是绝对路径+文件夹名称
mkdir(new_folder);  % mkdir()函数创建文件夹
cd(new_folder)
for i=1:100  
  eval(['fid=fopen(''a',num2str(i),'.txt''',',','''a+''',');'])%写入文件路径
  fprintf(fid,'%.4f\r\n',rand(10,1)); 
  fclose(fid);
end

Generate 100 txt files . As shown below:
Generate txt file


Second, the usage of eval function

This article uses the eval function extensively, and here is an introduction to the eval function. The eval function can calculate the generated string or numeric expression.
eval(expression) calculates the MATLAB code in the string expression. If you use eval in anonymous functions, nested functions, or functions that contain nested functions, the evaluation expression cannot create variables.
The format used is:
[output1,..., outputN] = eval (expression) The output of the expression is stored in the specified variable.

eval(['fid=fopen(''a',num2str(i),'.txt''',',','''a+''',');'])

The first 'of the two `` signs represents the escape character, and the second' sign of the two `` signs is the 'sign in the command. When using eval, you only need to write the sentence you want to express first, and then use it The 'sign is divided into a string of segments. Note that the above-mentioned' can be used as an escape character.
The sample code is as follows:

eval(['1+1'])

eval function


Three, batch read files

1. Read subfolder function

code show as below:

function [SubFolders] = GetFolders(ParentFolder)
SubFolderNames = dir(ParentFolder);
for i=1:length(SubFolderNames)
        if( isequal( SubFolderNames( i ).name, '.' )||...
        isequal( SubFolderNames( i ).name, '..')||...
        ~SubFolderNames( i ).isdir) % 如果不是目录则跳过
            continue;
        end
        SubFolder(i).SubFolderName = fullfile( ParentFolder, SubFolderNames( i ).name );
end
temp = {
    
    SubFolder.SubFolderName};
idx = cellfun(@(x)~isempty(x),temp,'UniformOutput',true); % 利用cellfun函数得到元胞数组中所有非空元素的下标
SubFolders = temp(idx);
end

The function of this function is to get the path of all subfolders under the parent folder. The input of the function is ParentFolder which is the path of the parent folder. For example: the output of the'D

:\Program Files'

function is that SubFolders is the path of the subfolders. As a cell array, for

example: {'D:\Program Files\FileZilla FTP Client\docs'}

The result of reading the file name is shown in the figure below:
Read file name

2. A brief introduction to some functions

dir function
Example :
dir ( '.'): List all subfolders and files in the current directory
Read the current folder name and the files in the current folder
cellfun function
operation target is cellfun cell array, may be utilized for any number of functions defined in the class
type of data or matrix calculations, cellfun You can use a custom function to process the cell array.
The calling format is:
A = cellfun(FUN, C)
cellfun example

3. Read the file name function of the specific format under the folder

code show as below:

function [FileNames] = GetFileNames(Path,Format)
fileFolder=fullfile(Path);
dirOutput=dir(fullfile(fileFolder,Format));
FileNames={
    
    dirOutput.name};
end

The function of this function is to obtain all file names in a certain format under a certain path.
The input Path of the function is the path to be obtained.

Example: The input Format of
the'D:\Program Files\FileZilla FTP Client\docs'

function is the file format of the path to be obtained.

Example:
' .txt',' .docx','*.png'


4. Batch read the file names under the folder

The file names created before are "1st", "2nd",.... Here, create a cell array to store the read file names and txt file data, and store the read daily data in a new matrix in the form of columns, and name them as "Q1", "Q2", ….

foldernames=GetFolders('D:\9月');
namelist=cell(1,length(foldernames));
for i=1:length(foldernames)
   a=foldernames{
    
    i};
   num=str2num(a(7:end-1));
   namelist{
    
    1,i}=GetFileNames(foldernames{
    
    i},'*.freq');
   P=cell(1,length(namelist{
    
    1,i}));
   for j=1:length(namelist{
    
    1,i})
       filename= namelist{
    
    i}{
    
    j};
       P{
    
    1,j} = importdata([foldernames{
    
    i},'\',filename]);
   end
   eval(['Q',num2str(num),'=[]']);
   for t=1:length(namelist{
    
    1,i})
      eval(['Q',num2str(num),'=[Q',num2str(num),',P{1,t}.data];']);
   end
end
total=[];
for i=1:length(foldernames)
    eval(['total=[total,Q',num2str(i),'];']);
end

Read the names of the 100 txt files in the'D:\September' directory that was just created, and the result is as shown in the figure below:

file name

Guess you like

Origin blog.csdn.net/weixin_40653652/article/details/108759707