Simpsons Rule: With for loops

6 visualizzazioni (ultimi 30 giorni)
Eric
Eric il 10 Mag 2015
Risposto: Malek Arnous il 20 Dic 2017
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)?

Risposta accettata

Walter Roberson
Walter Roberson il 10 Mag 2015
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 Commenti
Walter Roberson
Walter Roberson il 10 Mag 2015
What kind of n are you using?
Eric
Eric il 10 Mag 2015
I've been using 20,50,100,500,1000.

Accedi per commentare.

Più risposte (1)

Malek Arnous
Malek Arnous il 20 Dic 2017
yes

Categorie

Scopri di più su Numerical Integration and Differential Equations in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by