How to load data from structure with user input
Show older comments
A program I am using dumps collected data to a matlab structure with the first sub-structure being called the same as the filename and then the sub-sub-structures are all named consistently regardless of the filename. I'm trying to allow the user to input the filename and then use that to load the 1st sub-structure.
I can assign a filename in the script and assign data to a variable.
s=load('mile_out_45mph_run002.mat')
subs=(s.mile_out_45mph_run002);
subs_X=(subs.X); etc.
What I want is the user to tell me the filename:
filename=input('Enter filename without ".mat": ','s');
filenamemat=[filename,'.mat']
s=load(filenamemat);
subs=(s.filename);
but I get the error Reference to non-existent field 'filename' Which makes sense. It's actually called 'mile_out_45mph_run002'. How do I drill into the structure and get it to recognize that when I put
subs=(s.filename); I mean
subs=(s.mile_out_45mph_run002)
1 Comment
David Dominic
on 2 Oct 2015
Answers (1)
You need to use dynamic string syntax for accessing structure fields - e.g.
subs = s.( filename );
that way 'filename' can be a variable as you want, but it will get interpreted to the string contained in the variable when used as a field name of 's'.
This is shown on http://uk.mathworks.com/help/matlab/matlab_prog/generate-field-names-from-variables.html
I'm not quite sure what your parentheses are meaning though in:
subs = ( s.mile_out_45mph_run002 );
They don't do anything as far as I am aware.
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!