How to numerically solve and plot definite integral with variable upper limit

190 ビュー (過去 30 日間)
Where, the limit is P=0:0.1:pi
I have to integrate V and then plot P versus V graph
The x axis need to take as P
clc
close all;
V= @(t) (sin(t)-(x.*cos(t)).*sin(x);
P = 0:0.1:3.1416;
plot(P,V)

採用された回答

Alan Stevens
Alan Stevens 2022 年 3 月 3 日
Like so:
K= @(t) (sin(t)-t.*cos(t)).*sin(t);
P = 0:0.1:3.1416;
for i = 1:numel(P)
V(i) = integral(K,0,P(i));
end
plot(P,V),grid

その他の回答 (1 件)

John D'Errico
John D'Errico 2022 年 3 月 3 日
編集済み: John D'Errico 2022 年 3 月 3 日
There are many trivial ways. Off the top of my head ...
  1. Repeatedly integrate, using a tool like integral, from 0 to x, then plot the result, as a function of x. This scheme is wildly inefficient, since it forces the tool to redo the integration repeatedly over the lower parts of the domain. As such, this scheme is quadratic in time, based on the length of the interval.
  2. Symbolically integrate the expresssion, with a symbolic upper limit.
  3. Use cumtrapz.
  4. Use an ODE solver, something I think many people miss as a solution.
I won't even show how to do solution 1, since it is essentially never what I would recommend. The other solutions would all have their valid purposes though. For example:
K = @(t) (sin(t) - t.*cos(t)).*sin(t)
K = function_handle with value:
@(t)(sin(t)-t.*cos(t)).*sin(t)
(Solution 2)
syms T U
Kint = int(K(T),0,U)
Kint = 
fplot(Kint,[0,pi])
xlabel t
ylabel 'Cumulative integral'
grid on
So trivial to do, as long as the expression K has an analytical integral.
(Solution 3)
t = linspace(0,pi);
dt = t(2) - t(1);
plot(t,cumtrapz(dt,K(t)))
xlabel t
ylabel 'Cumulative integral'
grid on
(Solution 4)
ODEFUN = @(t,y) K(t);
y0 = 0;
[tout,yout] = ode45(ODEFUN,[0,pi],y0);
plot(tout,yout)
xlabel t
ylabel 'Cumulative integral'
grid on
As you can see, three essentially identical solutions.
If possible, you would almost always prefer the analytical solution, since it is exact to the extent computations can offer. The cumtrapz solution is the least accurate, since it employs what is implicitly an Euler method, but cumtrapz will be blindingly fast.. Finally, the ODE solver solution is a nice one, since it offers better control over the integration error than a trapezoidal integral, but it will work when no analytical solution can be found.

カテゴリ

Help Center および File ExchangeCalculus についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by