Search code examples
matlab

How to calculate the absolute error between two curves in MATLAB?


I got two curves in MATLAB and want to calculate the absolute error of them. The simplest way is to subtract them directly, but the problem is that each curve contains a different number of points. One contains 203 points, and the other contains 6623 points. Here is the plot: plot Is there any easy way to calculate the absolute error?


Solution

  • You need to create a third data set (x2_interp,y2_interp) which has the same values as your bigger data set and interpolate.

    This makes the two data sets the same size below are an example code

    % Example data (replace with your actual data)
    x1 = linspace(0, 10, 203);  % Assuming 203 points
    y1 = sin(x1);
    
    x2 = linspace(0, 10, 6623);  % Assuming 6623 points
    y2 = cos(x2);
    
    % Interpolate the second curve to have the same number of points as the first one
    x2_interp = linspace(min(x1), max(x1), numel(x1));
    y2_interp = interp1(x2, y2, x2_interp, 'linear');
    
    % Calculate the absolute error
    absolute_error = abs(y1 - y2_interp);
    
    % Plot the curves and the absolute error
    figure;
    subplot(3, 1, 1);
    plot(x1, y1, 'b-', 'LineWidth', 2);
    title('Curve 1');
    
    subplot(3, 1, 2);
    plot(x2, y2, 'r-', 'LineWidth', 2);
    title('Curve 2');
    
    subplot(3, 1, 3);
    plot(x1, absolute_error, 'g-', 'LineWidth', 2);
    title('Absolute Error');
    
    xlabel('X-axis');
    ylabel('Y-axis');