I'm trying to approximate the integral of a function using the composite Simpson's rule. This means I'll have to input a function, the maximum and minimum of the interval, and an number of integration nodes. Specifically, the exercise demands that I use the interval [0,10].
Now, I've written the code for the Simpson's rule, and it works. The problem is when I try to use an interval that starts with 0, like it happens in the exercise. For example, let's imagine I have this function:
x=1:100;
y(x)=x.^2;
plot(x,y(x));
When the Simpson rule calls for y(0), I get an error message indicating that the subscript must be a positive integer. Now, I understand why this must be. The variable x is defined as a vector, and there's no "0" subscript in that vector; it has to be 1, or 2,1, etc. But I need to be able to get a value for the function at 0 in order for the Simpson's rule to work. How can I circumvent this issue? Is there a way to define x so that y(x) can accept fractions, negative numbers or zero?
Here's my code for the CSR by the way:
function F=simpsonc(y,a,b,N)
h=(b-a)/N;
f=zeros(N+1,1);
f(1)=a;f(N+1)=b;y1=0;y2=0;
for z=2:N
f(z)=a+z*h;
end
for z=2:(N/2);
y2=y2+y(f(2*z-1));
end
for z=2:(N/2)-1;
y1=y1+y(f(2*z));
end
F=(h/3)*(y(a)+y(b)+4*y2+2*y1);
end

 Réponse acceptée

Roger Stafford
Roger Stafford le 18 Déc 2013

0 votes

Matlab won't let you use zero as an index value. You need to create an index variable that indexes values of x. Do this:
N = 100;
x = linspace(0,10,N);
y = x.^2;
% If you want to plot it
plot(x,y)
% Then integrate
for idx = 1:N
% Do Simpson's method using x(idx) and y(idx)
end

Plus de réponses (1)

Bernardo Teixeira
Bernardo Teixeira le 18 Déc 2013

0 votes

Thank you, but I'm having trouble understanding the last part, the integration. Where does x(idx) come in the code for the CSR? Should I use it instead of f?

Catégories

En savoir plus sur Programming dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by