How to plot midpoint method
41 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Fausto Pachecco Martínez
am 14 Nov. 2021
Kommentiert: Fausto Pachecco Martínez
am 18 Nov. 2021
I have this code in which I use the integration with the midpoint method (with rectangles), I already have the formulas but I don't know how to plot it.
clear all
clc
close all
%Ask the user for the expression
expression = input ("Please enter the expression: ", 's');
%Convert expression to function
f = inline(expression);
%Ask for limits of the interval to be evaluated
a = input ("Enter value of a: ");
b = input ("Enter value of b: ");
%Ask for the number of intervals
m = input ("Enter value of m: ");
%calculate the value of h
h = (b-a) / m;
%Add the area of each rectangle
S = 0;
for i = 1:m
%Calculate the area of a rectangle
S = S + (h) * (f((a+(a+h))/2));
a = a+h;
end
fprintf ("The approximate value of the integral of% s is:% 7.4f \ n", expression, S);
0 Kommentare
Akzeptierte Antwort
Pavan Guntha
am 17 Nov. 2021
Hello Fausto,
In order to plot the output of midpoint method, the data corresponding to the variable to be plotted needs to be included in the logic. For instance if the required data to be plotted is the Area of rectangle (S) per each interval (m), we need to track the area of rectangle in each iteration within the for loop as illustrated below:
for i = 1:m
%Calculate the area of a rectangle
S = S + (h) * (f((a+(a+h))/2));
area(i) = (h) * (f((a+(a+h))/2)); % Track area of rectangle in each iteration.
a = a+h;
end
plot(1:m, area); % Plots area of rectangle per each iteration.
You could have a look at the following resources which implements the similar task:
Hope this helps!
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Line Plots finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!