Access Variable in MATLAB Structure Using User Input

Click For Summary
SUMMARY

The discussion focuses on accessing a variable within a MATLAB structure using user input. The user, Peter, attempts to retrieve a value from a substructure named 'Expt_#' based on the input variable 'exptno'. The initial approach using the 'int2str' command is ineffective. The suggested solution involves creating a dynamic string with 'sprintf' to correctly reference the desired substructure, allowing for successful data retrieval from 'SpectralFrequencyTD2'.

PREREQUISITES
  • Familiarity with MATLAB structures and substructures
  • Understanding of user input handling in MATLAB
  • Knowledge of string manipulation functions in MATLAB, specifically 'sprintf'
  • Basic understanding of variable referencing in programming
NEXT STEPS
  • Learn about dynamic field names in MATLAB structures
  • Explore the use of 'sprintf' for string formatting in MATLAB
  • Investigate error handling for user input in MATLAB
  • Study examples of accessing nested structures in MATLAB
USEFUL FOR

Data analysts, MATLAB users, and programmers looking to manipulate and access structured data dynamically based on user input.

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 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 5 ·
Replies
5
Views
7K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
4K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 8 ·
Replies
8
Views
3K