Loading and saving sequence of files?

3 visualizzazioni (ultimi 30 giorni)
bio lim
bio lim il 7 Lug 2015
Commentato: bio lim il 7 Lug 2015
Hello. I have number of .mat files in a same directory that has a pattern SSR(Year)(Month)(Day). The problem is not every date is included in my files. The first three files out of 55 files are as follows.
SSR20140103.mat
SSR20140207.mat % All of the files have same variable name (data).
SSR20140208.mat
I would like to load all these 55 files into my script, run the program, and save accordingly with the name azimuth_SSR(Year)(Month)(Day) .
I have checked numerous websites and links, but most of them have pattern such as file(1) - file(20) .
Thanks.
Edit 1: So far, I am considering the following code.
file_name = inputdlg('Insert the file name.');
file_name = str2num(file_name{:});
load ('', 'file_name.mat')

Risposta accettata

Guillaume
Guillaume il 7 Lug 2015
Hardcoding the list of files is just asking for trouble. One day, one of the file will be missing and the code will fail. Or one day, there'll be one more file to process, and the code won't know about it.
Asking for the name of the file to process as a string, as you suggest, is also cumbersome. The user has to make sure it is typed correctly, and if it is not in the current folder also has to type the path. At the very list, use a file open dialog, so the user just has to pick the file from the list of files that exist.
In my opinion, the most robust and user friendly approach is simply to ask the filesystem for the list of files:
filelist = dir('SSR*.mat')';
for file = filelist
filename = file.name;
ymd = regexp(filename, 'SSR(\d{4})(\d{2})(\d{2}).mat', 'tokens', 'once')
if isempty(ymd)
continue; %not an SSRyyyymmdd file
end
ymd = cellfun(@str2double, ymd);
data = load(filename);
%do something with data.(filename)
end
  1 Commento
bio lim
bio lim il 7 Lug 2015
Thanks! Processing as a string was very cumbersome indeed.

Accedi per commentare.

Più risposte (1)

Stephen23
Stephen23 il 7 Lug 2015
Modificato: Stephen23 il 7 Lug 2015
Although beginners love making variable magically pop into existence in their workspaces, it is more robust to explicitly allocate to the output of load.
You can use dir to get a list of the files, and then load the data into a non-scalar structure. It would also be easy to obtain the path using uigetdir.
dir_path = 'sub_dir/project_dir/data_dir';
S = dir(fullfile(dir_path,'SSR*.mat'));
N = {S.name};
for k = numel(N):-1:1
out(k) = load(fullfile(dir_path,N{k}));
end
More detailed examples can be found here:

Categorie

Scopri di più su Workspace Variables and MAT Files in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by