How to integrate using a for loop and plot the result?

24 次查看(过去 30 天)
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!!

回答(1 个)

Chris Perkins
Chris Perkins 2018-1-8
编辑:Chris Perkins 2018-1-8
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 个评论
Géry van der Rest
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Graphics Performance 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by