Trapezoidal rule for loop
37 ビュー (過去 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!