尝试创建要绘制的点的数组。如何为阵列添加更多点?

时间:2019-04-02 20:01:06

标签: matlab

我试图做一个中点函数,该函数返回曲线下的总面积以及绘制每个矩形所需的点。我有这段代码,但是不确定如何正确地将更多点添加到数组中。

for index = 1:N
        x = [lines(index)-.5*dx(index), lines(index)-.5*dx(index), lines(index+1)-.5*dx(index), lines(index+1)-.5*dx(index)];
        y = [0 f(index) f(index) 0];
        ****points = [x;y] + points;

预期结果将是在中点绘制N个矩形的所有点。相反,它给了我一个错误。

使用+时出错 矩阵尺寸必须一致。

中点错误(第13行)             点= [x; y] +点;

1 个答案:

答案 0 :(得分:0)

更干净,更简短,没有for循环:

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