Trapezoidal rule for loop
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
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
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!