Trapezoidal rule for loop
16 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (1)
Geoff Hayes
il 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.
1 Commento
Katerin
il 31 Mar 2021
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.
Vedere anche
Categorie
Scopri di più su Get Started with MATLAB 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!