Trying to avoid using eval for looping through structures with data in the variable names.

2 visualizaciones (últimos 30 días)
I have a .mat file containing a bunch of structure variables which I need to loop through. The structure names differ based on the conditions of the trial whose data they represent. For example, subject1_treatment1_baseline_1, subject1_treatment1_post_1, subject1_treatment2_baseline_1, etc. Let's assume all the trials are subject1 and end with "_1". I realize this is not a good way to name these structures and that this information could be stored in fields within each, but the .mat file was exported from a program that automatically named the structures based on the data filename from which they were exported. So, at present, I have created cell arrays containing lists of the treatments and test times and a loop to cycle through the structure names that looks something like this:
treatment = {'treatment1','treatment2','treatment3'};
testtime = {'baseline','post'};
for t=1:length(treatment)
for tt=1:length(testtime)
trialname = ['subject1_' treatment{t} '_' testtime{tt} '_1'];
% Here's where I would like to use "trialname" to access the data in each structure in the workspace and perform calculations.
end
end
So, my question is, if the structures in the workspace are already named this way, is there a way I can access the structure in the workspace having the name stored in "trialname" without using eval?

Respuesta aceptada

Guillaume
Guillaume el 13 de Dic. de 2019
You could generate the variable name without a loop but unfortunately, yes in this case you'll be forced to use eval to access the content of these variables.
What I'd recommend is that you convert all these dynamic variables immediately at the start of your code into something more sensible like indeed structures with fields, or perhaps flatten it all into a table which is easier to use than multilevel structures, so that usage of eval is confined to one location.

Más respuestas (1)

Image Analyst
Image Analyst el 13 de Dic. de 2019
I think you should get a table, either directly from readtable() or by converting your struct to a table with struct2table(). Then you can just refer to a column number of the table using a numerical index rather than a name which might vary from one data set to the next.

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by