Importing multiple text files into MATLAB

조회 수: 8 (최근 30일)
Harshit Coutinho
Harshit Coutinho 2011년 2월 7일
I am trying to import multiple text files into MATLAB and save it as a .mat file after it has been imported. It works when I do it one file at a time by using the following command, for example:
T1_1041 = importdata('20101011_114543_VIN9375_Trigger01.txt');
but when I try to save the file name into a variable and try to use the importdata function with that variable as the file name. It does not work, like below:
myfile = '20101011_114543_VIN9375_Trigger01.txt'
[files,path] = uigetfile('MultiSelect', 'on');
for n=1:length(files);
myfile = files(n);
files(n).data=importdata(myfile);
save files(n).data
end
It gives an error inside the importdata function.
  댓글 수: 1
Jan
Jan 2011년 2월 7일
Please use the code formatting to improve the readability. If you get an error, it would be very helpful to post the error message.

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

채택된 답변

Jan
Jan 2011년 2월 7일
Your variable "files" is a cell string, therefore you need curly braces. During the loop you overwrite the original "files" by a struct. The variable "myfile" is overwritten also - it looks really confused.
[filenames, pathname] = uigetfile('MultiSelect', 'on');
filenames = cellstr(filenames); % EDITED
for n = 1:length(filenames)
afile = fullfile(pathname, filenames{n}); % EDITED
data = importdata(afile);
% Remove the file extension file the name:
[dummy, afilename] = fileparts(filenames{n});
save(afilename, 'data');
end
If you want to save all data in one MAT file, explain this again with more details.
  댓글 수: 4
Doug Eastman
Doug Eastman 2011년 2월 7일
Another question that would cause this problem - do you change directories in the file selection gui?
Jan
Jan 2011년 2월 7일
I've inserted two changes in the code. Please try it again.

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

추가 답변 (1개)

Doug Eastman
Doug Eastman 2011년 2월 7일
To be more robust to directory changes or single file selections, you might want to use something like the following:
[files,path] = uigetfile('MultiSelect', 'on');
if iscell(files)
for n = 1:length(files)
data = importdata(fullfile(path,files{n})); % fullfile including path
% save data
end
else
data = importdata(fullfile(path,files));
% save data
end

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by