How to numerically solve and plot definite integral with variable upper limit
조회 수: 202 (최근 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)
댓글 수: 0
채택된 답변
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
2022년 3월 3일
편집: John D'Errico
2022년 3월 3일
There are many trivial ways. Off the top of my head ...
- 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.
- Symbolically integrate the expresssion, with a symbolic upper limit.
- Use cumtrapz.
- 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)
(Solution 2)
syms T U
Kint = int(K(T),0,U)
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 Exchange에서 Calculus에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!