Search code examples
matlabplotaxes

plot two signals with different axis and limits in matlab


let's consider i am plotting two signals together on the same graph which has different limits and thus i want different axis

plot(a)
axis ([-2 10 -2 8])
hold 'on'
plot(b)
axis ([-1 4 -4 7])
hold 'off'

where 'a' and 'b' are two signal expression. the problem here is the signals are getting plot but only the second axis is working and plot a is not getting limited to the first specified axis. the reason being the second axis is obviously overwriting the first axes but any idea how to plot both signals with both axis limits?


Solution

  • You can select the data you wish to plot using logical operators.

    Let's consider the case for plot a.

    Assign each column of bs to a variable:

    x1 = bs(:,1)
    y1 = bs(:,2)
    

    Then select only the values that meet the condition specified:

    xPlot = x1(x1 > -2 & x1 < 10)
    yPlot = y1(y1 > -2 & y1 < 8)
    

    Assuming they both contain the same number of elements you can then plot them.

    If not, you need to pad the smaller array with Nan, for example, to avoid getting an error about mismatching dimension.

    Once you know which array is smaller, you can do it as follows. Let's say in this case xPlot is smaller than yPlot:

    m = max(numel(xPlot),numel(yPlot)) %// Just getting the larger dimension
    xPlot(numel(xPlot)+1:m) = NaN
    

    Now you can call

    plot(xPlot,yPlot,'b-','LineWidth',2)
    

    and that should work. The same applies for the b plot.

    Hope that helps!