open some .mat files (whose names are saved inside a cell)

Hi! I need to open some .mat files (whose names are saved inside the 'name_cell' cell).
I tried this way but, of course, it saves them all with the same name, overlapping them.
load name_cell.mat
folder = pwd;
for K = 1:height(name)
% Load file .mat
file = load(fullfile(folder,name{K,1}));
file = file.original_name; % all files are originally named 'original_name'
end
I would like to open them all with that specific name inside 'name_cell'.
Also, I need to save those open files in a single cell, like this:
matrix_cell = [{file_1};{file_2}];

 Accepted Answer

Where C is your cell array of filenames, and assuming exactly one array is saved in each MAT file:
D = C;
for k = 1:numel(C)
S = load(C{k});
D{k} = S.original_name;
end

4 Comments

Thank you for your reply, but the code does not work.
Unable to perform assignment because the left and right sides have a different number of elements.
Also consider that the .mat files (cells) in the 'folder' (from which I have to read them) are saved with names like 'file_1', 'file_2' etc. They take the name 'original_name' when I import them like this:
load file_1.mat %workspace: file_1 -> original_name
"but the code does not work. Unable to perform assignment because the left and right sides have a different number of elements."
Please upload a MAT sample file by clicking the paperclip button.
Note that I updated my answer to follow the approach you used. Please test it again.
Hi @Stephen23. I tried the code again and it works with the preceding code:
D = C;
for k = 1:numel(C)
S = load(C{k},'original_name');
D(k) = struct2cell(S);
end
I did something wrong in copying and pasting. But I need to read the .mat files from a 'folder' other than pwd. How can I modify the code you gave me?
"But I need to read the .mat files from a 'folder' other than pwd."
Provide the absolute/relative filepath and use FULLFILE:
P = 'absolute or relative filepath to where the files are saved';
D = C;
for k = 1:numel(C)
F = fullfile(P,C{k});
S = load(F,'original_name');
D(k) = struct2cell(S);
end

Sign in to comment.

More Answers (0)

Products

Release

R2021b

Community Treasure Hunt

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

Start Hunting!