Using a variable name as the name of a file structure

8 views (last 30 days)
I have a .mat file that is in a 3x3x4 structure format called buffet_acc.mat that has driver, bin, time and th within the .mat file. I am trying to make it such that I can tell the matlab script which file to open in real-time and not have to hard code the file name within the script itself (I have numerous files of this structure so hard coding the names would be a pain).
Here is where I ask for the filename to open
%The file, XYZ.mat, contains variables driver, bin, time and th
% Create a cell array of variable names to load.
filename = input('Input .mat File to Digitally Down Convert: ','s');
myVars = {'driver' , 'bin', 'time', 'th'};
load(filename, '-mat');
Which opens the file up (in my case it is buffet_acc.mat file), but when I try to index the file with
time=file_name(1, 3, 2).time;
I get the following error:
Undefined variable "file_name" or class "file_name".
Error in DDC (line 22)
time=file_name(1, 3, 2).time;
So, how do I fix this?
  1 Comment
Stephen23
Stephen23 on 15 Aug 2018
Edited: Stephen23 on 15 Aug 2018
"I have a .mat file that is in a 3x3x4 structure format called buffet_acc.mat "
It would help if you uploaded a sample file by clicking the paperclip item.
"Using a variable name as the name of a file structure"
Do not do that. That would force you into writing slow, complex, buggy code:

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 15 Aug 2018
Edited: Stephen23 on 15 Aug 2018
Although your explanation is not very clear, it seems that your .mat file contain one variable, which happens to be a structure. And that structure is what you want to access, without knowing its name. This is easy to achieve with struct2cell and some indexing, as long as the .mat file contains only one variable:
S = load(filename,'-mat');
C = struct2cell(S);
T = C{1};
T(1,3,2).time
  2 Comments
Stephen23
Stephen23 on 15 Aug 2018
@William Sims: I hope that it helps. Remember to click the accept button if this answer helped you: accepting answers is an easy way to thank the volunteers who help you on this forum.

Sign in to comment.

Tags

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!