Home > Software design >  how to load multiple files from directory into an array using matlab?
how to load multiple files from directory into an array using matlab?

Time:08-12

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.

CodePudding user response:

The load function loads what variables are in the .mat file with their real names into the current workspace. If you assign x as an output for load, the variables names appear as fields of a struct named x. For example, if first.mat contains v1, then, x = load('first.mat') will result in a x = struct with fields: v1.

So, in your case, assuming that you are sure that each .mat file contains a single variable, you can write the following loop to load all .mat files into a cell array arr.

fds = fileDatastore('*.mat', 'ReadFcn', @load);  % assume same folder
files = fds.Files;
for i = 1:length(files)
    % convert one-field struct into array, store in "arr"
    arr{i} = struct2array(load(files{i}));
end

And each arr{i} will now contain a variable, say vi, in lexicographic order. If the .mat file contains more than one variable, this code will break. If the files are in another folder, you can use their actual path and extension like this fileDatastore('path', 'ReadFcn', @load, 'FileExtensions','.mat').

  • Related