definite integral by using Midpoint rule
17 views (last 30 days)
Show older comments
What i have done is as below and how to code it as the diagram shown?
% Define the function to integrate using a function handle
f = @(x) nthroot(x,3);
% Define the interval and the number of subintervals
a = 0; b = 2; % Interval [a, b]
n = 10; % Number of subintervals
% Calculate the width of each subinterval
dx = (b - a) / n;
% Initialize the midpoint sum
mpr = 0;
% Calculate the sum for the Midpoint Rule
for i = 1:n
xi = a + (i-0.5)*dx; % Midpoint of the i-th subinterval
mpr = mpr + f(xi); % Add the value at the midpoint
end
% Calculate the integral approximation
I = dx * mpr;
% Display the result
fprintf('The approximate value of the integral is: %f\n', I);
% Plotting the function and the rectangles
x_vals = linspace(a, b, 1000); % Generate 1000 points between a and b
y_vals = arrayfun(f, x_vals); % Evaluate the function at each x value
% Plot each rectangle
for i = 1:n
xi = a + (i-0.5)*dx; % Midpoint of the i-th subinterval
% Plot the rectangle
rect_x = [xi - dx/2, xi - dx/2, xi + dx/2, xi + dx/2];
rect_y = [0, f(xi), f(xi), 0];
patch(rect_x, rect_y, 'm', 'EdgeColor', 'k', 'LineWidth', 1);
end
hold on; % Hold on to the current plot
% Plot the function
plot(x_vals, y_vals, 'r-', 'LineWidth', 3);
% Formatting the plot
xlabel('x-axis');
ylabel('y-axis');
box off;
hold off; % Release the plot hold
5 Comments
Answers (1)
Sandeep Mishra
on 17 Sep 2024
Hi L,
From the code snippet, I realized that you are working on plotting a curve with multiple rectangular plots and aim to fill the area between the curve and the rectangles with green colour, along with drawing vertical dotted lines at each midpoint.
Here’s a detailed approach for achieving both tasks
1. To achieve the patch, you can use the ‘fill’ function in MATLAB to create filled 2-D patches. Refer to the following code snippet that demonstrates how to apply the 'fill' function before adding the rectangular patches:
% Fill the area below the curve
fill([x_vals, fliplr(x_vals)], [y_vals, zeros(size(y_vals))], 'g');
% Plot each rectangle
2. The ‘plot’ function of MATLAB can be used to draw vertical dotted lines at each midpoint. Refer to the following code snippet that demonstrates how to use the 'plot' function to draw vertical dotted lines at each midpoint.
patch(rect_x, rect_y, 'm', 'EdgeColor', 'k', 'LineWidth', 1);
hold on
% Plotting vertical red dotted line at each midpoint
plot([xi, xi], [0, f(xi)], 'r--');
Please refer to the following MathWorks documentation for more information.
- ‘fill’ function: https://www.mathworks.com/help/releases/R2024a/matlab/ref/fill.html
- ‘fliplr’ function: https://www.mathworks.com/help/releases/R2024a/matlab/ref/fliplr.html
I hope this helps.
0 Comments
See Also
Categories
Find more on Encryption / Cryptography in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!