Integrating with trapz and calculate the error
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!
0 commentaires
Réponses (1)
Youssef Khmou
le 23 Nov 2014
Modifié(e) : Youssef Khmou
le 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)
0 commentaires
Voir également
Catégories
En savoir plus sur Numerical Integration and Differentiation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!