# Integrating with trapz and calculate the error

2 次查看（过去 30 天）
LilyAN 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 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!