Integrating with trapz and calculate the error

7 views (last 30 days)
LilyAN
LilyAN on 23 Nov 2014
Edited: Youssef Khmou on 23 Nov 2014
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!

Answers (1)

Youssef  Khmou
Youssef Khmou on 23 Nov 2014
Edited: Youssef Khmou on 23 Nov 2014
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)

Community Treasure Hunt

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

Start Hunting!