Search code examples
matlabmatlab-figurefillarearectangles

How can I plot filled rectangles as a backdrop for a desired target in MATLAB?


I have two datasets, one of which is a target position, and the other is the actual position. I would like to plot the target with a +/- acceptable range and then overlay with the actual. This question is only concerning the target position however.

I have unsuccessfully attempted the built in area, fill, and rectangle functions. Using code found on stackoverflow here, it is only correct in certain areas.

For example

y = [1 1 1 2 1 1 3 3 1 1 1 1 1 1 1]; % Target datum
y1 = y+1;               %variation in target size
y2 = y-1;
t = 1:15;
X=[t,fliplr(t)];        %create continuous x value array for plotting
Y=[y1,fliplr(y2)];      %create y values for out and then back
fill(X,Y,'b');

The figure produced looks like this:

I would prefer it to be filled within the red boxes drawn on here:

Thank you!


Solution

  • If you would just plot a function y against x, then you could use a stairs plot. Luckily for us, you can use the stairs function like:

    [xs,ys] = stairs(x,y);
    

    to create the vectors xs, ys which generate a stairs-plot when using the plot function. We can now use these vectors to generate the correct X and Y vectors for the fill function. Note that stairs generates column vectors, so we have to transpose them first:

    y = [1 1 1 2 1 1 3 3 1 1 1 1 1 1 1]; % Target datum
    y1 = y+1;               %variation in target size
    y2 = y-1;
    t = 1:15;
    [ts,ys1] = stairs(t,y1);
    [ts,ys2] = stairs(t,y2);
    X=[ts.',fliplr(ts.')];        %create continuous x value array for plotting
    Y=[ys1.',fliplr(ys2.')];      %create y values for out and then back
    fill(X,Y,'b');
    

    result