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

조회 수: 54 (최근 30일)
Andrea Sartori
Andrea Sartori 2018년 1월 4일
댓글: Géry van der Rest 2019년 5월 5일
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
Andrea Sartori
Andrea Sartori 2018년 1월 8일
Thank you Chris! You've been vey helpful
Géry van der Rest
Géry van der Rest 2019년 5월 5일
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에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by