Loading file and storing variable name as double in .mlx file
13 views (last 30 days)
Show older comments
Hello,
I am trying to create an interface using a .mlx file. I first have the user enter the filename into an 'edit field box' that loads this variable from the 'current folder'. This variable is then loaded. I then want to use this data for further processing. The issue is that I cannot use this data unless the preprocessing code is the same name as the loaded variable name.
For example, I have a file named 'Hammer1' that is a 240x1 array of numeric values. I enter 'Hammer1' into the 'edit field' box and save this as a string called hammerName. Next, I use the 'load' function to load the variable from the current folder. However, the variable in the workspace is 'Hammer1'. This is problematic beacuse if I want to do further processing (such as removing the DC component of the signal) I have to define the variable in this coden as 'Hammer1' in the code (see below). If the file name is 'Hammer2', then the code will not work because there would be an 'unrecognized field'.
Here is the code that would work:
clear;clc;close all
% Enter hammer file name
hammerName = "Hammer1";
% load hammer data
load(hammerName);
% remove DC component of signal
hammer = Hammer1 - mean(Hammer1);
If I use the same code above but load a file called 'Hammer2', this code would throw an error 'unrecognized field " Hammer2"'.
How can I load the variable from the 'edit field' box and create a general variable that can be used for further processing without having to define the file name in the code?
I've added the Hammer1 and Hammer2 .mat files.
0 Comments
Accepted Answer
Stephen23
on 11 Sep 2023
Edited: Stephen23
on 11 Sep 2023
To write robust code you should always LOAD into an output variable. Doing so also makes your task easier:
C = struct2cell(load('Hammer1.mat'));
assert(isscalar(C),'only one variable per MAT file!')
V = C{1}
hammer = V - mean(V)
Note for the future: it is unfortunate that you have been given such badly designed data: better data design would use exactly the same variable names in every MAT file. In future when you are designing your own projects you should use exactly the same variable name/s in every MAT file, because then your code will be simpler, more efficient, and more robust. If you have a good relationship to the people who came up with the badly designed data that you have been given then you coudl request that they fix their data design!
More Answers (0)
See Also
Categories
Find more on Sequence and Numeric Feature Data Workflows 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!