MATLAB Answers

0

Trapezoidal rule for loop

Latest activity Answered by Geoff Hayes
on 29 Apr 2019
So i have done the calculation for only one value of n = 200. The code that i have written is :
f = @(x)6*(cos(x/2)) .* (sin(x/2)).^2; % Defining given function
a = 0; % lower limit
b = pi; % upper limit
n = 200; % Number of intervals
h = (b-a)/n; % Width of each interval
s = 1/2 * (f(a) + f(b)); % Summation value
% make for loops to calculate values between the intervals
for i = 1 : n-1
s = s + f(a + i*h);
end
A = h * s; % The calcuated sum of all intervals
format long % Make the outcome to be in long format
disp(A) % Display the outcome
However now that i'm trying to make the loop for values of n = 20 , 50 , 100 , 150, 400. But im struggling to adjust the above code. any help is very appreciated.

  0 Comments

Sign in to comment.

Tags

Products


Release

R2018b

1 Answer

Answer by Geoff Hayes
on 29 Apr 2019

Nima - perhaps try
for n = [20,50,100,150,400]
f = @(x)6*(cos(x/2)) .* (sin(x/2)).^2; % Defining given function
a = 0; % lower limit
b = pi; % upper limit
h = (b-a)/n; % Width of each interval
s = 1/2 * (f(a) + f(b)); % Summation value
% make for loops to calculate values between the intervals
for i = 1 : n-1
s = s + f(a + i*h);
end
A = h * s; % The calcuated sum of all intervals
format long % Make the outcome to be in long format
fprintf('n = %d value=%f\n', n, A); % Display the outcome
end
I've replaced the call to display with fprintf to write out the value of n and A.

  0 Comments

Sign in to comment.