How to use a filename character array as a name of a variable?
17 vues (au cours des 30 derniers jours)
Irene Fernandez Ugidos le 10 Fév 2022
I'm running a code in which I'm quantifying certain parameters in a file.
- I have a character variable which is called filename, and contais the name of the file as described below.
- I also have the results of the quantification in a matrix variable called Results
I saved Results variable with the filename as name of the file, so right now I have a file called 3229_011_2.mat that contains the variable Results.
I made the same quantification in around 100 images, so now I have 100 files with different filenames but the same variable Results in it.
My intention is to concatenate ALL the Results variables in one single matrix, to work in all of them at the same time.
However, I tried to open all the files in Matlab, but since they all have the same variable name, I can't open them all at the same time to concatenate the matrices. For this reason, I thought that it would be useful to change the name of the variable Results to the name of the filename for each file at the moment that I'm doing the quantification and saving the file. In this way, I could open all the files and concatenate them.
This would be my goal:
Any ideas about how to solve this, or alternative approaches that I can use?
Plus de réponses (2)
AndresVar le 10 Fév 2022
Modifié(e) : AndresVar le 11 Fév 2022
You can use EVAL (see Stephen's comment to why this can cause error)
data = [....]; % your data
eval(sprintf('%s = data',varname);
OR an alternative to renaming the variables is that you can just load it under different names
data1 = load("file1.mat",'Results')
data2 = load("file2.mat",'Results') % then you have data2.Results and data1.Results
%% OR you can put it into a structure array.. you can make a loop
data(1) = load("file1.mat",'Results')
data(2) = load("file2.mat",'Results')
data(3) = load("file3.mat",'Results')
%% OR you if they are the same length you can just append it into a matrix
data = load("file1.mat",'Results')
data = [data load(iifile,'Results')]
Stephen23 le 11 Fév 2022
Modifié(e) : Stephen23 le 11 Fév 2022
A very neat and simple approach is to import the data into the same structure that DIR returns:
P = 'absolute or relative path to where the files are saved';
S = dir(fullfile(P,'*.mat'));
for k = 1:numel(S)
F = fullfile(P,S(k.name));
D = load(F);
S(k).data = D.Results; % your well-designed .mat files make this easy!
All of the imported file data is in the structure S, for example the second file:
S(2).name % filename
S(2).data % the Results data
You can easily use a comma-separated list to concatenate all of the Results data into one matric, if so desired, depending on the orientation of the data in Results, something like one of these:
M = horzcat(S.data)
M = vertcat(S.data)