Plot Error and Residual Between Two Signals
The standard way to visualize signal discrepancies is a synchronized two-panel plot: the top panel overlays both signals, and the bottom panel displays the residual error.
Method 1: Two-Panel Stacked Subplot (Signals + Residual)
% Generate sample signals (Reference vs Measured with noise)
t = linspace(0, 1, 1000);
y_true = 5 * sin(2 * pi * 5 * t);
y_meas = y_true + 0.3 * randn(size(t));
% Calculate error metrics
residual = y_true - y_meas;
mae = mean(abs(residual));
rmse = sqrt(mean(residual.^2));
% Create synchronized figure
figure('Color', 'w', 'Position', [100, 100, 750, 500]);
% Top Panel: Signal Comparison
ax1 = subplot(2, 1, 1);
plot(t, y_true, 'b-', 'LineWidth', 1.5, 'DisplayName', 'Reference');
hold on;
plot(t, y_meas, 'r--', 'LineWidth', 1.0, 'DisplayName', 'Measured');
ylabel('Amplitude');
title(sprintf('Signal Comparison (RMSE = %.3f, MAE = %.3f)', rmse, mae));
legend('Location', 'northeast');
grid on;
% Bottom Panel: Residual Error
ax2 = subplot(2, 1, 2);
plot(t, residual, 'k-', 'LineWidth', 1.0, 'DisplayName', 'Residual (True - Meas)');
hold on;
yline(0, 'r--', 'LineWidth', 1.2); % Zero reference line
xlabel('Time (s)');
ylabel('Error (e = y_{true} - y_{meas})');
title('Residual Error');
grid on;
% Synchronize X-axis zoom and pan
linkaxes([ax1, ax2], 'x');
Method 2: Shaded Error Band (Direct Fill)
This method fills the area between two curves to highlight divergence directly on a single plot.
t = linspace(0, 2*pi, 300);
sig1 = sin(t);
sig2 = sin(t) + 0.15 * cos(3*t);
figure('Color', 'w');
% Fill region between curves
fill([t, fliplr(t)], [sig1, fliplr(sig2)], [0.9 0.8 0.8], ...
'EdgeColor', 'none', 'DisplayName', 'Discrepancy');
hold on;
plot(t, sig1, 'b-', 'LineWidth', 1.5, 'DisplayName', 'Signal 1');
plot(t, sig2, 'r-', 'LineWidth', 1.5, 'DisplayName', 'Signal 2');
xlabel('Time');
ylabel('Amplitude');
title('Error Highlighted with Shaded Fill');
legend('Location', 'northeast');
grid on;
Method 3: Stem Plot for Discrete/Sampled Residuals
t_sample = 0:0.02:0.5;
ref = sin(2*pi*4*t_sample);
est = ref + 0.1 * randn(size(t_sample));
res = ref - est;
figure('Color', 'w');
stem(t_sample, res, 'filled', 'Color', [0.8 0.2 0.2], 'LineWidth', 1.2);
yline(0, 'k-');
xlabel('Time (s)');
ylabel('Residual Error');
title('Discrete Residual Stem Plot');
grid on;
Best Practice: Always use
linkaxes([ax1, ax2], 'x') in two-panel plots. When you zoom into any section of the signals in the top plot, the bottom residual axis zooms to the exact same time window automatically.Need a Custom Version or Complete Simulation for This Problem?
Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.
Explore similar technical troubleshooting questions and verified MATLAB solutions: