MATLAB Access Variable in MATLAB Structure Using User Input

AI Thread Summary
In this discussion, the user seeks assistance with MATLAB for data analysis, specifically in accessing substructures within a main structure based on user input. The user has a structure named "experiments" containing substructures like "Expt_1", "Expt_2", etc., and wants to retrieve a value from a specific substructure using a variable called "exptno". The initial attempt to use the int2str command to dynamically access the substructures was unsuccessful. A suggested solution involves using the sprintf function to create a string that represents the substructure name, allowing for correct access to the desired value, "SpectralFrequencyTD2". This approach emphasizes the need for proper string formatting to dynamically reference structure fields in MATLAB.
peterjaybee
Messages
62
Reaction score
0
Hi I am trying to use MATLAB for some data analysis. I start by getting user input for a variable called exptno, Then I want to access a location in a structure, but to do this I need to append the variable exptno to the name of the structure. Ill try and give an example to hopefully make it cleared.

I have structure called experiments and substructures called Expt_1, Expt_2, Expt_3, Expt_4 etc... and I want to get a value from in the Expt_# substructure (called spectralfrequencyTD2) based on the value that the user has input to exptno.

The original method I tried was as follows using the int2str command. This doesn't work, but hopefully it will give you some idea of what I m trying to do.

LarmorFreq = experiments.Expt_int2str(exptno).SpectralFrequencyTD2

Thanks,

Peter
 
Physics news on Phys.org
try creating a string using string_const = sprintf('Expt_%i', num);

LarmorFreq = experiments.string_const.SpectralFrequency TD2
 

Similar threads

Replies
4
Views
1K
Replies
3
Views
2K
Replies
5
Views
3K
Replies
3
Views
2K
Replies
4
Views
3K
Replies
4
Views
1K
Replies
1
Views
2K
Back
Top