Loading file and storing variable name as double in .mlx file

조회 수: 14 (최근 30일)
FsC
FsC 2023년 9월 11일
댓글: FsC 2023년 9월 11일
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.

채택된 답변

Stephen23
Stephen23 2023년 9월 11일
편집: Stephen23 2023년 9월 11일
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}
V = 240×1
0.0015 0.0015 0.0015 0.0015 0.0015 0.0015 0.0015 0.0015 0.0015 0.0015
hammer = V - mean(V)
hammer = 240×1
1.0e-05 * 0.0551 -0.0455 -0.0835 0.1244 0.0573 0.0528 0.0975 0.1221 0.1892 0.2652
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!

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Sequence and Numeric Feature Data Workflows에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by