How to use the trapezium rule
5 views (last 30 days)
Show older comments
Hi,
I've been trying to figure out how to use the trapezium rule and completely failing, since I'm a bit of a simpleton at Matlab.
I'm integrating the product of two functions and trying to find the value of the definite integral using the trapezium rule.
This is my code:
syms x f=(((x.^2)-1)^n);
Pn=(1/((2.^n).*factorial(n))).*diff(f,x,n); Pm=(1/((2.^m).*factorial(m))).*diff(f,x,m);
P=Pn.*Pm
x = -1 :0.1: 1;
y=P;
trapz(y,x)
I keep getting these errors:
??? Error using ==> trapz at 59 LENGTH(X) must equal the length of the first non-singleton dimension of Y.
Error in ==> Question7b at 11 trapz(y,x)
Thanks.
0 Comments
Answers (2)
Roger Stafford
on 10 May 2013
Pm would be the m-th Legendre Polynomial except that, as you have defined it, it appears to involve the m-th derivative of the n-th power of x^2-1, not its m-th power. I see no way for the m value to automatically be substituted for n in that formula. You may have to define another function, g, which uses m for this purpose.
Also I see no place where you have given n and m specific values before calling on 'trapz'. It does not know how to do its computation without being given specific numerical values for all its variables. As far as I know, it is incapable of producing a symbolic answer.
In fact n and m need to be defined before matlab can produce a function into which x values could be substituted. The form of the functions depends on the values of n and m.
I don't have an updated symbolic toolbox to check this with, but your error message indicates that the vector length of y is incorrect. You had better chose a small n and m and manually check out the forms of the Pn and Pm functions. Also check out that the proper substitution has been made of the x numerical values in getting y. With your x you should get a vector length for y of 21. If not, you need to find out why not.
Finally I notice that your call on 'trapz' is erroneous. It should be
trapz(x,y)
not
trapz(y,x).
(Note that you can also use 0.1*trapz(y) with your x sub-intervals all that same length.)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!