how to refer variable from string name
Afficher commentaires plus anciens
Hello,
I have an array of string names for variables I need to use, and variables with such names in workspace. How should I refer? for example I need to find mean for variables with names 'm1_n' 'm3_n' specified in array A. The names will be different all the time -- I cant just write mean(m1_n) I need to do it through A and indexing, but in A names are strings.
5 commentaires
KSSV
le 18 Mai 2021
How you created that data? How the data is?
Yelena Bibineyshvili
le 18 Mai 2021
Stephen23
le 19 Mai 2021
"they are created in another programm"
Sure, but so far you have not explained the most important piece of information: how did those variables get into your MATLAB worskpace? Did you write them out by hand? Or did some script create them? Or are they loaded from a file?
If you loaded them from a .mat file then the best solution is to load into an output variable (a scalar structure), which you should always be doing anyway, and then simply access the fields of that structure.
Yelena Bibineyshvili
le 19 Mai 2021
Stephen23
le 19 Mai 2021
"yes they are created by other script"
The best** solution is to fix that other script so that it does not store meta-data (e.g. indices) in variable names.
** best in the sense more efficient (run-time, programming time, debugging time, maintenance time), easier to understand (simpler code, no obfuscation, clear where data comes from), easier to debug (variable highlighting, static code checking, mlint checking), etc.
Réponse acceptée
Plus de réponses (1)
Can you do this? Yes.
Rather than defining variables with numbered names, consider putting them in an array.
x1 = 1:5;
x2 = x1 + 5;
x3 = x1 + 10;
% or
xmat = [x1; x2; x3];
To iterate through x1, x2, and x3 I'd need to use the discouraged approach. To iterate through the rows of xmat is easy.
for k = 1:size(xmat, 1) % or 1:height(xmat)
y = xmat(k, :)
% Do something with y
end
4 commentaires
Yelena Bibineyshvili
le 18 Mai 2021
Yelena Bibineyshvili
le 18 Mai 2021
x = cell(1, 3);
for k = 1:3
x{k} = magic(k+2);
end
for k = 1:3
fprintf("Element %d of x is of size %s.\n", k, mat2str(size(x{k})))
end
Yelena Bibineyshvili
le 18 Mai 2021
Catégories
En savoir plus sur Variables dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!