The Simpson's 1-3 (h / 3) method in Matlab

39 visualizzazioni (ultimi 30 giorni)
Rooter Boy
Rooter Boy il 19 Gen 2021
Risposto: Steven Lord il 19 Gen 2021
The C code that finds the following integral according to the Simpson's 1-3 (h / 3) method is given below. Fill in the blanks on the code appropriately.
I want to solve this question below in Matlab but i didn't do it. This is simple question but i can't do it. If someone will help me, i will be very happy.
C code version:
I tried this code block in Matlab:
% Ask for user input
% Lower bound (a)
a = input('What is your lower bound (a)?')
% Upper bound (b)
b = input('What is your upper bound (b)?')
% Subintervals
N = input('How many subintervals (N)?')
% Defining function
f = @(x,e) (e*x+sin(x))
% Finding h
h=(b-a)/N;
% Finding the values of x for each interval
x=linspace(a,b,N);
% Calculating the integral
for i = 1:N-1
I(i)= (h/3)*(f(x(i))+(4*f((x(i)+x(i+1))/2))+f(x(i+1)));
end
answer1 = sum(I)
disp(I)
% adding f(b) to sum
val2=ff(length(xx));
sum=val1+val2+sum;% set sum
% set result
result=sum*h/3;

Risposte (1)

Steven Lord
Steven Lord il 19 Gen 2021
% Ask for user input
% Lower bound (a)
a = input('What is your lower bound (a)?')
% Upper bound (b)
b = input('What is your upper bound (b)?')
% Subintervals
N = input('How many subintervals (N)?')
% Defining function
f = @(x,e) (e*x+sin(x))
You've defined your function to accept two inputs but ...
% Finding h
h=(b-a)/N;
% Finding the values of x for each interval
x=linspace(a,b,N);
% Calculating the integral
for i = 1:N-1
I(i)= (h/3)*(f(x(i))+(4*f((x(i)+x(i+1))/2))+f(x(i+1)));
you call your function with just one. Since the first term in f is supposed to compute the exponential of x, that's not the right way to define it.
f = @(x) exp(x)+sin(x); % Added by Steve L
Now this f matches the problem statement and it can be (must be) called with just one input argument.
end
answer1 = sum(I)
Since this is a homework assignment I would define answer1 to be 0 before the loop and write the body of the loop closer to the way the C code does, just adding to answer1 each time. The mod function will be of use to you if you do. Keep in mind that MATLAB indexing is 1-based unlike C's 0-based indexing.
disp(I)
% adding f(b) to sum
val2=ff(length(xx));
Typo. ff should be f, and you shouldn't call it with length(x) as input. You should call it with the last element of x, x(end).
sum=val1+val2+sum;% set sum
% set result
result=sum*h/3;
You can't use sum both as a variable and as a function in the same script. Change the two instances of sum in the last line to answer1. In addition, you haven't defined a variable val1 in your code.

Categorie

Scopri di più su Sparse Matrices 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