Sum function handles efficiently
9 views (last 30 days)
Show older comments
I need to solve an ODE where the motion is determined by charges in position (where and ). For the sake of simplicity let's just assume that and that the dynamic given by the particle in is given by (i.e. I need to solve). I just need to solve an ODE where the motion is determined by the effects of the charges combined, and in my case the dynamic is simply given by the sum of the functions . I tried definining function handles stored in a 2 dimensional array of size , where in position I store the function . Then, I would need to define and solve an ODE where the motion is determined by F. The way I did this is by recursion, i.e.:
%I have already defined f as a 2D array, where f{i,j}=f_{i,j} described
%in the text
F= @(t,x) 0;
for i= 1:1:N
for j=1:1:N
F= @(t,x) F(t,x) + f{i,j}(t,x)
end
end
After this, I use the solve function:
fun = ode(ODEFcn=@(t,x) F(t,x),InitialTime=0,InitialValue=[0,0]); % Set up the problem by creating an ode object
sol = solve(fun,0,100); % Solve it over the interval [0,10]
The problem is: the performance is very bad. I already see this when defining F. I think there might be some issues with the recursion, nad maybe there's a better way for defining F, in such a way that the performances get better.
4 Comments
Alex
on 26 Jun 2024
Not sure if this makes it any better, but you can avoid the recursion and define your combined ODE in two lines:
[i,j] = meshgrid(1:N, 1:N);
F = @(t,x)sum(arrayfun(@(i,j)f{i,j}(t,x),i(:),j(:)));
Answers (0)
See Also
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!