To fix the issue of mismatched vector lengths when plotting the filtered signals, we need to ensure that the time vector matches the length of the filtered data for each window size. This can be achieved by creating a new “filtered_time” vector that starts at the index corresponding to the end of window, ensuring it aligns with the shorter “filtered_z” vector.
Next, by iterating over each window size and plotting the results within the loop, we can maintain all plots on the same graph.
Additionally, using the “DisplayName” property in the “plot” function allows for the dynamic labelling of each line, and calling the “legend show” after plotting displays a legend that helps distinguish between raw and filtered signals.
Please find below the updated MATLAB code with the required changes:
data = csvread('z_flip_data_60BPM.csv');
z_raw = data(:,2); % Raw signal from data collection
time = data(:,1)/1000; % Time converted to seconds
figure;
plot(time, z_raw, 'r');
hold on
windows = [10, 50, 100];
% Loop over each window size
for w = windows
% Initialize filtered_z for the current window size
filtered_z = zeros(1, length(z_raw) - w);
% Moving average window filter
for i = w+1:length(z_raw)
filtered_z(i-w) = mean(z_raw(i-w:i));
end
% Adjust time vector for plotting filtered data
filtered_time = time(w+1:end);
% Plot the filtered data
plot(filtered_time, filtered_z, 'DisplayName', sprintf('Window %d', w));
end
legend show
xlabel('Time (s)')
ylabel('Amplitude')
title('Raw and Filtered Signals')
hold off
Please find attached the documentation of functions used for reference:
I hope this assists in resolving the issue.