Hi, So I have a question where I have to use Simpsons rule to integrate (1-x^3)*sin(x) + exp(x^2/20) between -1 and 4 with 20 intervals. The function has 4 inputs, f(x), a,b (start and end points) and n intervals
I know that I can make this code simpler with the sum function but unfortunately I have to use loops for this exercise.
My code looks like this:
function integral = simpsonsrule(f,a,b,n)
h = (b-a)/n;
x = linspace(a,b,n);
x4=0;
x2=0;
for j=2:2:b
x4 = x4 + f(x4);
end
for k=3:2:b
x2= x2 + f(x2);
end
integral = (h/3)*(f(a)+ f(b) + 4*(x4)+ 2*(x2));
end
And I'm calling it like this:
clear;
integral = simpsonsrule((1-x.^3)*sin(x) + exp(x.^2/20),-1,4,20)
But I'm getting the error: Undefined function or variable 'x'. but haven't I defined it with x=linspace(a,b,n)?

 채택된 답변

Walter Roberson
Walter Roberson 2015년 5월 10일

0 개 추천

integral = simpsonsrule(@(x) (1-x.^3)*sin(x) + exp(x.^2/20),-1,4,20)
You need the @(x) to make an anonymous function

댓글 수: 8

Thanks Walter.
The program works but I now see the code is wrong as I'm getting incorrect integrals. I changed my loop code to:
x4=0;
x2=0;
for j=2:2:b
x4 = x4 + f(j);
end
for k=3:2:b
x2 = x2 + f(k);
end
When I increase n intervals, the integral decreases. I think its calculating the area of the individual interval area but not adding them all up.
for j=2:2:b
x4 = x4 + f(x(j));
end
No luck. Integral still keeps decreasing as n increases and doesn't stabilise. I'm thinking maybe I have to force the use of absolute values.
function integral = simpsonsrule(f,a,b,n)
h = (b-a)/n;
x = linspace(a,b,n);
x4=0;
x2=0;
for j=2:2:b
x4 = x4 + f(x(j));
end
for k=3:2:b
x2 = x2 + f(x(k));
end
integral = (h/3)*(f(x(a))+ f(x(b)) + 4*(x4)+ 2*(x2));
end
Walter Roberson
Walter Roberson 2015년 5월 10일
Your start and end points are numeric, not indices into x, so in your integral line you should be using f(a) and f(b)
Eric
Eric 2015년 5월 10일
Yup, changed that earlier but same result.
You need a small correction to the anonymous function. You currently have
@(x) (1-x.^3)*sin(x) + exp(x.^2/20)
and you need instead
@(x) (1-x.^3).*sin(x) + exp(x.^2/20)
I don't think it will change your output
Walter Roberson
Walter Roberson 2015년 5월 10일
What kind of n are you using?
Eric
Eric 2015년 5월 10일
I've been using 20,50,100,500,1000.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

카테고리

도움말 센터File Exchange에서 Numerical Integration and Differential Equations에 대해 자세히 알아보기

질문:

2015년 5월 10일

답변:

2017년 12월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by