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

96 ビュー (過去 30 日間)
Andrea Sartori
Andrea Sartori 2018 年 1 月 4 日
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 Center および File ExchangeGraphics Performance についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by