How can I access structures through strings?
58 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I am trying to access specific parts of the structure by appending a string to it. Instead of struct.field, I want to do p = 'field', struct.p (something along those lines). Reason why I am doing this is to avoid using a bunch of if statements for my hundred-some variables or structure fields that I will be looking at. If there is a better way of doing it, please let me know.
for j = 1:length(MATFilesInfo)%list of MAT files in directory neeed to be covered
load (char(MATFilesInfo(j)));%loads through each MAT file individually
for i = 1:length(varnames/3)%need to run analysis on every set of 3 variables
enblcndtionname = who('-regexp',char(varnames(3*(i - 1)+1)));%This the enable condition
var1name = who('-regexp',char(varnames(3*(i - 1)+2)));%First variable comparison e.g. EGRDELAVE
var2name = who('-regexp',char(varnames(3*(i - 1)+3)));%Second variable comparison e.g. EGRIDIFF
enblcndholder = eval(enblcndtionname);%allows matlab to recognize string as variable
var1holder = eval(var1name);%allows matlab to recognize string as variable
var2holder = eval(var2name);%allows matlab to recognize string as variable
smallest = [length(enblcndholder), length(var1holder), length(var2holder)];%use the smallest
scalar = min(smallest);%use the smallest length as a scalar for
%larger length arrays to go through the
%same number of points as the smaller array
OBDVariables(i).var1name = enblcndholder(1:length(enblcndholder)/scalar:length(enblcndholder));%This is where the part of the code will not work because
OBDVariables(i).char(varnames(3*(i - 1)+2)) = var1holder(1:length(var1holder)/scalar:length(var1holder));%I cannot find the appropriate syntax to manipulate the structure like so
OBDVariables(i).char(varnames(3*(i - 1)+3)) = var2holder(1:length(var2holder)/scalar:length(var2holder));%
end
end
I am a newbie at coding so please let me know if something else is grossly inefficient or if there is a better way to do things.
Thanks,
0 commentaires
Réponse acceptée
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Variables dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!