天天看點

matlab-梯形積分

1、内容簡介

2、内容說明

clear
 clc
 close all
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 f = @(x) 2*x.^2-1; % 定義函數
 % ==============================
 xstart = 0;
 xstop = 2;
 num_steps = 20;
 xpoints = linspace(xstart,xstop,num_steps);
 ypoints = f(xpoints); % 調用之前的函數
 integral = trap_integrate(ypoints,xstart,xstop,num_steps)
 % 理論積分數值 16/3-2
% ==============================
 xstart = 0;
 xstop = 2;
 num_steps = 50;
 xpoints = linspace(xstart,xstop,num_steps);
 ypoints = f(xpoints);
 integral = trap_integrate(ypoints,xstart,xstop,num_steps)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 f = @(x) tan(x);
 % ==============================
 xstart = 0;
 xstop = pi/3;
 num_steps = 100;
 xpoints = linspace(xstart,xstop,num_steps);
 ypoints = f(xpoints);
 integral = trap_integrate(ypoints,xstart,xstop,num_steps)
% ==============================
 xstart = 0;
 xstop = pi/3;
 num_steps = 200;
 xpoints = linspace(xstart,xstop,num_steps);
 ypoints = f(xpoints);
 integral = trap_integrate(ypoints,xstart,xstop,num_steps)
 %% 
 C = 33.3e-6;
 R = 200;
 sys = tf([1 0],[R 1/C]); %傳遞函數
 step(sys)
 xstart=0;
 xstop=10;
 num_steps=1000;
 t = linspace(xstart,xstop,num_steps); % 時間 
 U = @(t)200*cos(300*t);
 in = U(t);
 i = lsim(sys,in,t);% 仿真
 plot(t,i)
 integral = trap_integrate(i.^2,xstart,xstop,num_steps);
 rms = sqrt(integral/(xstop-xstart))      
function integral = trap_integrate(ypoints,xstart,xstop,num_steps)
data = linspace(xstart,xstop,num_steps); %生成x資料
integral = 0;
if length(data)~=length(ypoints)
    error('輸入的x,y資料長度不相等,請檢查輸入') % 判斷輸入的資料是不是合理
end
step =data(2)- data(1); % x資料間隔
for i = 1:num_steps-1
    integral = integral+(ypoints(i)+ypoints(i+1))*step/2; % 梯形積分累加
end      

3、仿真分析

4、參考論文

繼續閱讀