How to set file name to load based on user input

Hi,
I have a GUI created in guide which contains a pop-up menu with various options available, e.g. 'test1', ''test2', 'test3', these are names of .mat files the user might want to load. The GUI also has a push button which when pressed would load the selected .mat file from the pop-up menu and add some data to it. My code for loading the .mat file currently looks like this..
foo = get(handles.popup2,'Value');
if foo == 1
fname = 'test1'
elseif foo == 2
fname = 'test2'
elseif foo == 3
fname = 'test3'
end
folder = 'C:\Documents and Settings\usr\My Documents\MATLAB\'
Database = load(fullfile(folder,fname)
The problem is that the code loads a 1x1 struct of the entire contents of the directory. Where am I going wrong?
Thanks in advance, Joel

Answers (1)

foo_names = get(handles.popup2, 'String');
foo = get(handles.popup2,'Value');
if isempty(foo)
fprintf(2, 'You need to select a value\n');
return
end
fname = foo_names{foo};
folder = 'C:\Documents and Settings\usr\My Documents\MATLAB\';
full_name = fullfile(folder,[fname, '.mat']);
try
Database = load(full_name);
catch
fprintf(2, 'Opps, I failed to load the file %s\n', full_name);
return
end
Now Database is going to be a struct with one field for each variable stored in the .mat file. This is how load() is defined when you ask it to return a value. You can refer to appropriate fields of the structure
Database.mydata
for example to access the variable stored as mydata in the .mat file.

2 Comments

Hi Walter, thanks for the quick response. Unfortunately, your answer is still giving the same result. Database is returning a struct with a field for every variable stored in the C:\Documents and Settings\usr\My Documents\MATLAB\ directory. If I try
Database.test1
All I get is a return of the filename, e.g.
test1.mat
Please show
whos -file test1.mat
Also please show what full_name comes out to be.

Sign in to comment.

Tags

Asked:

on 30 Nov 2015

Edited:

on 30 Nov 2015

Community Treasure Hunt

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

Start Hunting!