Search code examples
matlabmatlab-figure

How to smooth a stairstep-like graph in Matlab


The stairstep-look of the graph is unintentional. When I plot the same-sized vectors Arb and V (plot (Arb, V, 'r')) I get the following graph:

enter image description here

To make it smoother, I tried using 1-D data interpolation, interp1, as follows:

xq = 0:0.001:max(Arb);
Vq = interp1 (Arb, V, xq);
plot (xq, Vq);

However, I get this error message:

Error using interp1>reshapeAndSortXandV (line 416)
X must be a vector.

Error in interp1 (line 92)
    [X,V,orig_size_v] = reshapeAndSortXandV(varargin{1},varargin{2})

Solution

  • interp1 will use linear interpolation on your data so it won't help you much. One thing you can try is to use a cubic spline with interp1 but again given the nature of the data I don't think it will help much. e.g.

    Alternative 1. Cubic Spline

    xq = 0:0.001:max(Arb);
    Vq = interp1 (Arb, V, xq, 'spline');
    plot (xq, Vq);
    

    Alternative 2. Polynomial fit

    Another alternative you can try is, polynomial interpolation using polyfit. e.g.

    p = polifit(Arb, V, 2); % I think a 2nd order polynomial should do
    xq = 0:0.001:max(Arb);
    Vq = polyval(p, xq);
    plot (xq, Vq);
    

    Alternative 3. Alpha-beta filter

    Last but not least, another thing to try is to use an smoothing alpha-beta filter on your V data. One possible implementation can be:

    % x is the input data
    % a is the "smoothing" factor from [0, 1]
    % a = 0 full smoothing
    % a = 1 no smoothing
    function xflt  = alphaBeta(x, a)
        xflt = zeros(1,length(x));
        xflt(1) = x(1);
    
        a = max(min(a, 1), 0); % Bound coefficient between 0 and 1;
    
        for n = 2:1:length(x);
            xflt(n) = a * x(n) + (1 - a) * xflt(n-1);
        end
    end
    

    Usage:

    plot (Arb, alphaBeta(V, 0.65), 'r')