Dynamically Make a Variable Name
27 次查看(过去 30 天)
显示 更早的评论
Hello,
I would like to make a variable name created from user input data, then make that variable a structure.
Right now I have a 1 x 2 structure called AllPlotInformation and I save the variable to a .mat file with a unique name (APlotData.mat, BPlotData.mat, etc). My issue is that if someone wants to load multiple files, the variable is called AllPlotInformation for every file so it gets overwritten. I would like a unique variable name for the struct so it will appear in the workspace when multiple files are loaded.
Here is an example:
letter= 'A';
color= 'blue;
tableVariablename= letter + color + "Table";
%this part I don't know how to make happen
AblueTable= struct('data1', data1, 'data2', data2_);
1 个评论
Stephen23
2024-4-3
编辑:Stephen23
2024-4-3
"My issue is that if someone wants to load multiple files, the variable is called AllPlotInformation for every file so it gets overwritten"
Then you should be asking about that:
" I would like a unique variable name for the struct so it will appear in the workspace when multiple files are loaded."
Ugh, do NOT do that.
Unless you really want to force yourself into writing slow, complex, inefficient, obfuscated, buggy code that is hard to debug:
You have well-designed data (every MAT file uses the same variable names) which allows you to easily write efficient and robust code to process that data. Do not ruin that good data design with dynamic variable names!
采纳的回答
Paul
2024-4-2
Hi Summer,
One option would be to use load with an output argument, which will put all of the variables the .mat file in a struct named by that output variable.
% create sme example data and files
AllPlotInformation = 1;
save file1 AllPlotInformation
AllPlotInformation = 2;
save file2 AllPlotInformation
s1 = load('file1')
s2 = load('file2')
0 个评论
更多回答(1 个)
Stephen23
2024-4-3
编辑:Stephen23
2024-4-3
This is MATLAB so the best solution is to use indexing, just as the MATLAB documentation shows:
So far there is nothing in your question that prevents you from using neater, simpler, more efficient indexing.
For example:
P = 'absolute or relative path to where the files are saved';
S = dir(fullfile(P,'*.mat'));
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
S(k).API = load(F).AllPlotInformation;
end
API = vertcat(S.API) % optional
All of the imported file data is stored in the structure S, which you can easily access using indexing. For example, the 2nd file:
S(2).name % filename
S(2).API % AllPlotInformation
Indexing is much better than your approach: neater, simpler, easier, more efficient, much more robust.
The optional line with VERTCAT concatenates all of the imported 1x2 structures into one Nx2 structure.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!