How to integrate using a for loop and plot the result?
54 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi, I need to integrate a function using LOOP FOR and plot the result. For example f(x)= cos(x) with 0<=x<=pi. Practically I want to divide the area under the curve in a lot of trapezes, calculate their area and sum them. Can you help me? thank you!!
0 Kommentare
Antworten (1)
Chris Perkins
am 8 Jan. 2018
Bearbeitet: Chris Perkins
am 8 Jan. 2018
Hi Andrea,
You can use "linspace" to create a large number of points over your given range, then calculate the function value at each iteration of the loop, and then calculate the area using the function value and the size of the step. You could plot the area at each step of the loop, or any other values, depending on what exactly you want to plot.
Here's a quick example, using cos(x):
totalArea = 0;
x = linspace(0,pi,10000);
f = zeros(1,length(x));
stepSize = x(2) - x(1);
for i = 1:length(x)
f(i) = cos(x(i));
totalArea = totalArea + f(i) * stepSize;
end
disp(totalArea);
Alternatively, if you only need to find the integral, you can use the function "integral", as described on the following documentation page:
2 Kommentare
Géry van der Rest
am 5 Mai 2019
Hi,
Is is possible to do the same procedure, but if the function that I want to integrate is the product of several functions? for example, I want to integrate the function h(x)=(3x^2+x)*(e^3x) by doing a for loop. Can I use the same strategy as the one explained here ?
Thank you very much.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!