Variable within a Variable

2 Ansichten (letzte 30 Tage)
Jan Vincent Kleu
Jan Vincent Kleu am 12 Jul. 2022
Beantwortet: Steven Lord am 12 Jul. 2022
file0=uigetfile;
%further file loadings up to file10
for i=48:57
f=1;
k=char(i);
filename=append('file',k);
load (file0,'ansT');
%file0 is a char named PID_SER[...]
[~, baseFileName, ~] = fileparts(filename);
end
Within the for loop, I want to count up the files to be processed later in the loop (making several plots).
In order to correctly name the plots, I neet to read the title of the file loaded. I get the filename via the fileparts function, while the filename is saved under a char named file0 (created during load). As I need count up the files in each loop, I created the variable filename and appended file with the variable k (as a char).
How do I get the fileparts function so that I get the result if i was to put in the variable file0?

Akzeptierte Antwort

Steven Lord
Steven Lord am 12 Jul. 2022
Am I correct that you're hoping to have the variable that stores the file name be file1 at the second iteration, file2 at the third, etc.? If so, while you can dynamically create variables with numbered names like x1, x2, x3, etc. the general consensus is that you should not. That Answers post explains why this is generally discouraged and offers several alternative approaches.
In this case I'd probably use a string array or perhaps a cell array. If I knew I wanted to retrieve a specific number of files (7 in this case) I'd preallocate. I'm using hard-coded strings instead of uigetfile so I can run this in Answers and show you the technique.
listOfDwarfs = strings(7, 1)
listOfDwarfs = 7×1 string array
"" "" "" "" "" "" ""
F = "Bashful.txt";
% Do something with F
listOfDwarfs(1) = F
listOfDwarfs = 7×1 string array
"Bashful.txt" "" "" "" "" "" ""
F = "Doc.txt";
% Do something with this F
listOfDwarfs(2) = F
listOfDwarfs = 7×1 string array
"Bashful.txt" "Doc.txt" "" "" "" "" ""
F = "Dopey.txt";
% Do something with this F
listOfDwarfs(3) = F
listOfDwarfs = 7×1 string array
"Bashful.txt" "Doc.txt" "Dopey.txt" "" "" "" ""
% Continue with Grumpy.txt, Happy.txt, Sleepy.txt, and Sneezy.txt

Weitere Antworten (0)

Kategorien

Mehr zu Entering Commands finden Sie in Help Center und File Exchange

Produkte


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by