Integrating with trapz and calculate the error

조회 수: 5 (최근 30일)
LilyAN
LilyAN 2014년 11월 23일
편집: Youssef Khmou 2014년 11월 23일
The question is as follow: Modify the code so it calculates the error of "definite integral (sin(x)dx) from 0 to pi" as a function of array elements (use array lengths of 10 to a million in decade intervals). Add commands to the code so it plots the error on a logarithmic scale
Actually i'm new in MATLAB (first week into it)..and I'm messing around with all the functions here
The script I wrote is here:
n=[10:10:1e6];
integral=linspace(0,1e6,0);
for i=1:length(n);
x=linspace(0,pi,n(i));
trapz(i)=trapz(x,sin(x));
integral(i)=int(sin(x),0,pi);
error(i)=(traps(i)-integral(i));
end
plot(error(i))
Could anyone please tell me what's wrong with the script? Thanks in advance!

답변 (1개)

Youssef  Khmou
Youssef Khmou 2014년 11월 23일
편집: Youssef Khmou 2014년 11월 23일
The first remark is that names of built in functions must not be used as variables ( trapz in this case ), second remark is int function is for symbolic computation, so you need to use symbolic variable. Your solution is good enough, here is an enhanced version using only 100 as limit :
n=[10:10:100];
syms X
F=int(sin(X),0,pi);
% F equals 2 but F is symbolic again, so you take value
t2=2*ones(size(n));
for i=1:length(n);
x=linspace(0,pi,n(i));
t(i)=trapz(x,sin(x));
error(i)=(t(i)-t2(i));
end
semilogy(error)

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by