how to load multiple files from directory into an array using matlab?
39 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
molan
el 9 de Ag. de 2022
Comentada: Walter Roberson
el 10 de Ag. de 2022
i have a directory that includes some .mat files , i want to load all these files into an array .
i tried something like this :;
x1=load('C:\Users\me\OneDrive\Desktop\project\a\first_file.mat')
x2=load('C:\Users\me\OneDrive\Desktop\project\a\second_file.mat')
... and so on for all the files in the directory , and at the end i want to have an array such that:
arr(1)=x1 ...
how can i access the directory and load all of the files at the same time into an array ?
ps: i tried using path before and dir but then i got this error :
> error using eval , undefind function 'workspacefun' for input
> arguments of type struct
thank you in advance.
5 comentarios
Respuesta aceptada
Walter Roberson
el 10 de Ag. de 2022
dinfo = dir('*.mat');
filenames = {dinfo.name};
for K = 1 : length(filenames)
temp = load(filenames{i});
FN = fieldnames(temp);
FN1 = FN{1};
thisdata = temp.(FN1);
if K == 1
all_data = thisdata;
else
all_data(:,:,K) = thisdata;
end
end
The code would be easier if they all had the same variable name (and the variable name was known.) This version of the code does not assume that they all have the same variable name. This code will not error if there is more than one variable in the file -- but if there is, then which variable is loaded might not always be the first alphabetically.
2 comentarios
Walter Roberson
el 10 de Ag. de 2022
directory_to_process = 'appropriate_path_goes_here';
dinfo = dir( fullfile(directory_to_process, '*.mat') );
filenames = fullfile({dinfo.folder}, {dinfo.name});
all_data = [];
for K = 1 : length(filenames)
temp = load(filenames{i});
FN = fieldnames(temp);
FN1 = FN{1};
thisdata = temp.(FN1);
if K == 1
all_data = thisdata;
else
all_data(:,:,K) = thisdata;
end
end
Más respuestas (0)
Ver también
Categorías
Más información sobre Debugging and Analysis en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!