MATLAB Answers

Using variables from a .mat data file in a user-defined function

7 views (last 30 days)
Jacob Forbes
Jacob Forbes on 24 Sep 2021
Answered: Walter Roberson on 25 Sep 2021
I'm writing a function that will read data from a .mat data file and interpret a message using ASCII binary. The input data has a series of frequencies, the target frequencies being from 400-750 Hz by increments of 50. If there is a peak at one of the frequencies it is interpreted as a 1 and stored in a string, otherwise it is interpreted as a zero. The error I am running into is the function is not recognizing the variables that are defined within the .mat file that I load into in my main script. The script and the function are shown below. Any help is appreciated I'm still fairly new to MATLAB.
load('message_1.mat'); %load in data signal
window_size = 50e-3; %set the window size to 50 ms
samples_per_window = window_size*fs; %calcalute number of samples in each
%window
total_windows = length(tone)/samples_per_window; %total number of sample
%windows
Message = [];
for i = 1:total_windows %repeats loop for total number of sample windows
window = tone((i-1)*samples_per_window+1:i*samples_per_window); %define
%the window within the tone data
[X,f] = myFFT(window, fs); %perform the fourier transform
Message = decipher(window, fs);
it should be noted I am using another user-defined function here myFFT
and then the user-defined function, decipher
function [Message] = decipher(window,fs)
binarystring = [];
for n = 1:8
if abs(X(abs(f-(350+50*n)) < .01)) > 0.015
binarystring=[binarystring '1'];
else
binarystring=[binarystring '0'];
end
end
hold = char(bin2dec(binarystring)); % ASSIGN TO TEMP VAR
Message = [Message hold]; % PUT VAR IN STRING TO DISPLAY LATER
disp(Message)
end
  1 Comment
Stephen
Stephen on 25 Sep 2021
If you want to learn how to write robust MATLAB code and avoid these kind of errors, then LOAD into an output variable (which is a scalar structure) and access its fields:
S = load('message_1.mat'); %load in data signal
Your current approach (spamming unknown variables straight into the workspace) is always liable to these kind of bugs.

Sign in to comment.

Answers (2)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 25 Sep 2021
Note that the variable names stored and loaded from your *.mat file have to be consistent with the variable names called in your main m-file or to be renamed respectively so that your main m-file recalls the loaded variables correctly.

Walter Roberson
Walter Roberson on 25 Sep 2021
function [Message] = decipher(window,fs)
if abs(X(abs(f-(350+50*n)) < .01)) > 0.015
How is the code to know where to look for X? How is it to know where to look for f?

Community Treasure Hunt

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

Start Hunting!