- Please learn how to format code in this forum. This has been discussed repeatedly, such that you will find the required information, when you search for them.
- Whenever you mention that you get an error, post the complete error message also.
- Post the command, which causes the error.
- Please use meaningful tags: All questions in this forum concern "Matlab", and most of them "Matlab function"s. Therefore I've removed these tags.
- Square brackets are needed to concatenate elements to a vector only. As far as I can see, all occurrences in your code are not needed. In the calculation of "Q", round parenthesis are sufficient. Do not insert square brackets in Matlab only because the mathematical notations contains them.
Matlab simpsons rule function
5 次查看(过去 30 天)
显示 更早的评论
I am trying to write a matlab script for simpsons rule given the function, upper and lower bounds, and number of points. I have written it to use the simpsons 1/3 rule for an odd number of points and a combination of the 1/3 and 3/8 rules for an even number of points. These are my scripts so far, and I am getting an error. If anyone could add some insight, that'd be great!
function [y] = func(x) y=1-exp(-3*x)
function [Q] = Simpsons(func,rl,ru,n)
h=(ru-rl)/(n-1); x=[rl:h:ru];
if mod(n,1) == 0 Q=(ru-rl)/(n*3)*[func(x(1))+4*sum(func(x(2:2:n)))+2*func(x(3:2:n-1))+func(x(n))]
end
if mod(n,1)== 0
Q1=h/3*[func(x(1))+4*sum(func(x(2:2:n-3)))+2*sum(func(x(3:2:n-4)))+func(x(n-3))]
Q2=3*h/8*(func(x(n-2))+3*sum(func(x(n-2:1:n)))+func(x(n)))
Q=Q1+Q2
end
1 个评论
Jan
2012-12-9
编辑:Jan
2012-12-10
回答(1 个)
Jan
2012-12-10
编辑:Jan
2012-12-10
The code function checks for mod(n,1) == 0 twice. But do you really want to call this function with a non-integer value of n?! I assume you want if mod(n, 2), ..., else, ... end.
There is a missing sum() in the first formula to get Q.
It is at least confusing, that you use "func" as input to the Simpsons function, although this is the name of the function to be integrated already. This is not necessarily an error, when you do not forget to add the leading @ character when calling the Simpsons.
The indices are not correct. E.g. the element x(n) appears twice in the summation. In addition it looks, like you have mixed the Simpson rules for quadratic and cubic interpolations (the "3/8 rule"). I suggest to study http://en.wikipedia.org/wiki/Simpson%27s_rule. Asking Google for a clean implementation of Simpson's rule would be a good idea also.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Numerical Integration and Differential Equations 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!