Trapezoidal rule for loop

7 次查看(过去 30 天)
NIMA RAHMANI MEHDIABADI
评论: Katerin 2021-3-31
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.

回答(1 个)

Geoff Hayes
Geoff Hayes 2019-4-29
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.
  1 个评论
Katerin
Katerin 2021-3-31
I have the similar code in Matlab, but I have to implement errors between each step.
It should be sth like error1=abs(outcome1-outcome2); error2=abs(outcome2-outcome3) and so on..
I am pretty desperate so any help would be appreciated.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by