How to load files identified by the matlab function of "dir"?

36 次查看(过去 30 天)
I have many files in a folder named "mat_files". What I want to do is to load the files and get their values. Below is my code:
a = dir('mat_files');
for i = 3:length(a);
filename = a(i).name;
load strcat('mat_files/', filename);
end;
This is the error:
Error using load
Unable to read file 'filename': no such file or directory.
When I type a(3).name in the command window, I get the correct filename of "ex0219.mat". Of course, I can load the data by typing "load ex0219.mat". Clearly load a(3).name does not work. I also tried load (a(3).name), which does not work either.
  3 个评论
Leon
Leon 2013-12-8
编辑:Leon 2013-12-8
Thank you so much for the tip. I missed the path of the files when using load. But why
load strcat('mat_files/', filename) ;
does not work either?

请先登录,再进行评论。

采纳的回答

Image Analyst
Image Analyst 2013-12-8
A smiple modification gives you the answer:
myFolder = 'C:\users\leon\documents'; % or whatever.
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, '*.mat');
matFiles = dir(filePattern);
for k = 1:length(matFiles)
baseFileName = matFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
storedStructure = load(fullFileName);
% Now do whatever you need to do with the structure you recalled.
end
  1 个评论
Leon
Leon 2013-12-8
编辑:Leon 2013-12-8
Thank you for the code. Glad to learn the use of "fullfile". It works flawlessly!

请先登录,再进行评论。

更多回答(1 个)

sixwwwwww
sixwwwwww 2013-12-8
编辑:sixwwwwww 2013-12-8
you should read files like this:
directoryString = 'YourDirectory';
files = dir(strcat(directoryString,'*.mat'));
names = {files.name}
I hope it helps. Good luck!
  8 个评论
Leon
Leon 2013-12-8
编辑:Leon 2013-12-8
>> filename{1}
ans =
ex0209a.mat
After I replace filename with filename{1}, it is working now. Thank you so much!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by