How to integrate using a for loop and plot the result?
56 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Chris Perkins
el 8 de En. de 2018
Editada: Chris Perkins
el 8 de En. de 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 comentarios
Géry van der Rest
el 5 de Mayo de 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.
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!