Search code examples
matlabgraphgraphicsmatlab-figure

How to use the fill() function to fill between sinusoidal?


x = [-pi/2:0.01:pi/2]';
y = (sin(x))';
plot(x,y)


h = fill(x,y,'r');
set(h,'facealpha',.5)

set(gca, 'XTick',-pi/2:pi/2:pi/2,'XTickLabel',{'-\pi/2','0','\pi/2'});
set(gca, 'YTick',0:1:1, 'YTickLabel',{'0','Fmax'});

text(0,0,'  O','HorizontalAlignment','left');

grid on

I'm trying to fill the space between the curve y = sin(x) and y = 0.

I'm not sure how to do this since what i've tried clearly doesn't do this. Any help is appreciated.


Solution

  • If you want to use fill you need to close the polygon by adding two points that go back to the starting point:

    h = fill([x(:); x(end); x(1)],[y(:); 0; 0], 'r');
    

    Or, more simply, use area instead of fill:

    h = area(x, y, 'FaceColor', 'r');