How to save a variable from workspace into a .mat file, but the variable obtains value from a for loop?

1 view (last 30 days)
I have this code and i want to save the variable x from workspace into a file clc;
clear;
close all;
% Parameters
sampling_frequency = 1000; % Sampling frequency in Hz
duration = 5; % Duration of signal acquisition in seconds
num_samples = sampling_frequency * duration;
% Initialize variables
time = (0:num_samples-1) / sampling_frequency;
x = zeros(1, num_samples);
% Connect to Arduino
a = arduino();
% Bandpass filter parameters
low_cutoff_frequency = 6; % Low cutoff frequency in Hz
high_cutoff_frequency = 400; % High cutoff frequency in Hz
% Design the bandpass filter
[b, a_filter] = butter(2, [low_cutoff_frequency, high_cutoff_frequency] / (sampling_frequency / 2), 'bandpass'); %Normalized between [0 1]
% Plot for real-time visualization of raw signal
figure('Name', 'Real-Time Raw EMG Signal');
h_raw = plot(nan, nan); % Initialize plot with NaN
grid on;
title('Real-Time Raw EMG Signal');
xlabel('Time (s)');
ylabel('Voltage (V)');
xlim([0, duration]); % Adjust xlim as needed
ylim([0, 5]); % Adjust ylim according to expected voltage range
% Plot for real-time visualization of filtered signal
figure('Name', 'Real-Time Filtered EMG Signal');
h_filtered = plot(nan, nan); % Initialize plot with NaN
grid on;
title('Real-Time Filtered EMG Signal');
xlabel('Time (s)');
ylabel('Voltage (V)');
xlim([0, duration]); % Adjust xlim as needed
ylim([0, 5]); % Adjust ylim according to expected voltage range
% Start loop to acquire signal
for i = 1:num_samples
% Read voltage
raw_voltage = readVoltage(a, 'A0');
% Store raw voltage
x(i) = raw_voltage;
% Apply bandpass filter to the signal up to current point if enough data points are collected
if i >= 25
filtered_signal = filtfilt(b, a_filter, x(1:i));
% Remove DC offset by subtracting the mean of the filtered signal
filtered_signal = filtered_signal - mean(filtered_signal);
% Update plot for filtered signal
set(h_filtered, 'YData', filtered_signal, 'XData', time(1:i));
end
% Update plot for raw signal
set(h_raw, 'YData', x(1:i), 'XData', time(1:i));
drawnow;
end
save('EMG_data.mat', 'x',);
It doesn't create the .mat file and I suppose the problem is that i stop the iteration very early. But I want to save any values that are obtained until any iteration. How can I fix that?

Answers (1)

Animesh
Animesh on 31 Jul 2024
To ensure that the variable "x" is saved to a MAT file even if the iteration is stopped early, you can use a "try-catch" block in MATLAB. Using this, regardless of whether the loop completes or is interrupted, the variable "x" will be saved.
try
for i = 1:num_samples
%code
end
catch ME
disp('Loop interrupted.');
disp(ME.message);
end
save('EMG_data.mat', 'x');
You can refer the following MathWorks documentation for more information:

Community Treasure Hunt

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

Start Hunting!