Convert data form .txt file into .mat file

조회 수: 18 (최근 30일)
Tiago André
Tiago André 2021년 12월 19일
댓글: Voss 2021년 12월 20일
Hey guys, hope you doing well.
I need help converting the data of hundreds of .txt files into one matlab file. Each text file has 3 columns. I was thinking about extracting the data of each column and then save it as a variable into one .mat file. In the end i would like to have one matlab file with 3 columns/variables.
This is the code that i have, but its not working for my needs. I'm having problems extracting the data of each column.
Files_September = dir('202109*.txt')
files = numel(Files_September);
for k = 1:files
files2 = Files_September(k).name;
fid = fopen(files2);
data = fscanf(fid, '%c')
fclose(fid);
save('September','data')
end
I'm attatching one text file so that you know what type of files im working with.
Thank you for your help.

채택된 답변

Voss
Voss 2021년 12월 19일
Each time through the loop data contains the data from the current file, so that when you do save, only the current file's data will be saved in the mat-file, overwriting what was in the mat-file before (if anything). If you want one mat-file with the data from all the text files, you can accumulate the data in the loop and then save it once after the loop.
Files_September = dir('202109*.txt')
files = numel(Files_September);
data = '';
for k = 1:files
files2 = Files_September(k).name;
fid = fopen(files2);
new_data = fscanf(fid, '%c');
fclose(fid);
data = [data new_data];
end
save('September','data')
Now data will be a character array of all the text in all the files and it will be stored in the file 'September.mat'. Maybe this is sufficient and maybe not; I don't know what kind of data is in those text files. Each file contains three columns, but three columns of what? Numbers? Names of countries? And are there line(s) of text at the top with column titles? The answers to those types of questions would determine which method is best for reading the files and accumulating the data properly.
Can you attach an example text file to your question so that we may help further? Thanks.
  댓글 수: 5
Tiago André
Tiago André 2021년 12월 19일
I've found a solution for this. I was using the variable 'data' instead of the 'new_data' in the september file. Thank you for help!
I just have one question. Being the data saved as one variable, instead of 3, i can still use just one or different columns for graphics and data analysis, right?
Voss
Voss 2021년 12월 20일
Correct. You can use any or all columns for whatever you want to do.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by