Using integral
I don t think there is a way to have MATLAB return the integral along the path, so you are correct in performing the integration one Δx at a time.
The slowness comes from the loop and subsequent restart of every integral
call.
You can avoid the loop by posing the integral over every interval as a vector-valued function.
www.un.org/Depts/DGACM/index_spanish.htm
The Math
Suppose we divide x into N-1 intervals with N total boundaries and denote an interval boundary as xn where n ∈{1,2,3...,N} such that x1 ≤ x2 ≤ x3 ... ≤ xN.
Then any integral over the interval would be
https://i.stack.imgur.com/7BoLp.gif” alt=“integral in terms of x”/>
Using the u-substitution:
整体成为:
<Δx>sub>n = xn - xn-1
www.un.org/Depts/DGACM/index_spanish.htm
The Code
So now, we can pose the interval integration of any function by specifying the lower bound xn-1, specifying the interval width Δx, and integrating from 0 to 1.
The best part is that if the lower bound and interval widths are vectors, we can create a vector-valued function in terms of u and have integral
integrate with the option ArrayValued = true
.
x = a:0.1:b;
xnm1 = x(1:end-1);
dx = x(2:end) - xnm1;
fx = @(x) 2*sin(3*x);
f = @(u) dx .* fx(dx*u+xnm1);
y = cumsum([0,integral(@(u)f(u),0,1, ArrayValued ,true)]);
<代码>cumsum指出,每一组成部分在一定间隔期内必须增加以前的间隔值。
在我的机器上,这至少比 lo版要快,而且随着间隔期增加,情况会更好。
www.un.org/Depts/DGACM/index_spanish.htm
Using ode45
Use can also use ode45
to perform the integration.
It is not nearly as efficient as the integral
method, but it may be easier conceptually and look cleaner.
In fact, ode45
is about 10 times slower than the integral method above when required to return an absolute error on par with that of integral
.
a = 0;
b = 10;
% These options are necessary to approach the accuracy of integral
opt = odeset( RelTol ,100*eps(), AbsTol ,eps());
sol = ode45(@(x,y) 2*sin(3*x),[a,b],0,opt);
x = a:0.01:b;
yint = deval(sol,x);