Variable within a Variable

4 次查看(过去 30 天)
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?

采纳的回答

Steven Lord
Steven Lord 2022-7-12
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by