MATLAB code for Simpson\'s Rule. Please help fix my code. I am trying to use the
ID: 3719960 • Letter: M
Question
MATLAB code for Simpson's Rule.
Please help fix my code. I am trying to use the example to verify my code, but my code is wrong.
clc
clear all
close all
%Equation = input('Enter Function: ');
a = input('Enter lower limit: ');
b = input('Enter upper limit: ');
n = input('Enter number of sub-intervals: ');
f = @(x) 1/(x+1);
T = a:n:b;
w = (b-a)/n;
j = f(a);
k = f(b);
area1 = 1;
c = a + w;
while (c < b)
area1 = area1 + 4 * f(c);
c = c + w + w;
end
area2 = 0;
e = a + w + w;
while (e < b)
area2 = area2 + 2 * f(e);
e = e + w + w;
end
g = (j + area1 + area2 + k);
fprintf('Area using Simpsons Rule = %f ', g);
Example. Use Simpson's rule with n 6 to estimate 1 +x3 dx. Solution. For n = 6, we have ?x = 461 = 0.5. We compute the values of yo, y?, ??, . . . , 16. 11.5 2 2.5 3.5 24.375 3 16.62528 43.875 65 Therefore, ???? dz 0.5(V2 + 4v 4.375+2(3) + 4v 16.625 + 2v 28 +A/43 875 + 35 12.871Explanation / Answer
a = input('Enter lower limit: ');
b = input('Enter upper limit: ');
n = input('Enter number of sub-intervals: ');
f = @(x) 1./(x+1);
h=(b-a)/n;
ar=a:h:b;
I=(h/3)*(f(ar(1))+2*sum(f(ar(3:2:end-1)))+4*sum(f(ar(2:2:end)))+f(ar(end)));%according to simpson's rule
fprintf('Area using Simpsons Rule = %f ', I);
%if any query, please tell in comments
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.