Search code examples
matlabplot

MATLAB how to plot a discrete function without vertical lines, only levels


I have something like this:

t = [-1 0 1 2 3 4 5];
ft= [ 0 0 0 0 1 1 1];

I want to plot only horizontal levels high\low without vertical lines:

enter image description here


Solution

  • If you don't mind the vertical lines, it's really simple to just use the stairs(x,t) function. Otherwise you can create your own function that deals with pairs of points to generate lines and plot them all individually using hold on.

    function stairs2(x,y)
        hold on;
        for i=1:length(x)-1
            plot(x(i:i+1),[y(i) y(i)]);
        end
        hold off;
    end
    

    Then just call stairs2(x,t) as per your example above, and set appropriate zoom/axes.

    Alternately, this is a different way that only uses ONE call to plot:

    function stairs2(x,y)
        for i=1:length(x)-1
            A(:,i) = [x(i) x(i+1)];
            B(:,i) = [y(i) y(i)];
        end
        plot(A,B,'b');
    end