Get the filename of a loaded file
Show older comments
Hi,
I have a script that loads a file and do some data plotting. I am loading different files each time I run the script. I manually edit the file name since every time the name is different and comming from an unrelated system.
My script reads the file as follows:
load('\Data_record_file_20220714T121615.mat');
Question:
How can I register the file name in a variable? I want to later use the file name in a string (after trimming it) so that I can automatically include the file name on the plot title.
Thank you.
Fabián
Accepted Answer
More Answers (2)
桂生 李
on 3 Aug 2022
1 vote
try
[FileName, FilePath] = uigetfile;
Walter Roberson
on 3 Aug 2022
filename = '\Data_record_file_20220714T121615.mat';
load(filename);
[~, basename, ~] = fileparts(filename);
title( "Analysis of " + basename)
Note: we do not recommend that form of load(). We recommend that you assign the output of load() to a variable, which gives you a struct array with one field for each loaded variable; you would then pull fields out of the struct as needed. This is more robust and more efficient, and is needed if you later want to do code generation. There are situations in which MATLAB will ignore variables created by load() that does not have an output variable name.
3 Comments
Fabian Grodek
on 3 Aug 2022
Walter Roberson
on 3 Aug 2022
load(filename); is not recommended. load_data = load(filename); is recommended instead.
Fabian Grodek
on 3 Aug 2022
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!