Более чистые и короткие без петель:
clear
%% setup
f=@(x) sin(x)+x.^2; %function
x0=-pi; x1=pi; %range
N=20; %num of mid points
%% calculations
xs=linspace(x0,x1,N+1); %rectangles xs
xm=(xs(1:end-1)+xs(2:end))/2; %N mid points
ym=f(xm); %value at midpoint
midpoint_area=sum(ym)*(x1-x0)/N;
%% print results
trapezoid_area=trapz(xm,ym); %compare to trapezoid matlab function
fprintf('midpoint_area=%.2f, trapezoid_area=%.2f\n',midpoint_area,trapezoid_area)
%% plots
figure(1); cla;
fplot(f,[x0,x1]);
hold on;
xrects=[xs(1),repelem(xs(2:end-1),2),xs(end)] ; %for ploting. each xs used for 2 mid points values
yrects=repelem(ym,2);
stem(xrects,yrects,'Color','black','Marker','none') %plot rectangles
plot(xrects,yrects,'Color','black') %plot rectangles
if N<40
plot(xm,ym,'Og') %midpoint
text(xm,ym,strcat('\leftarrow',sprintfc('[%.1f',xm),sprintfc(',%.1f] ',ym)))
end