필터 지우기
필터 지우기

Sum function handles efficiently

조회 수: 32 (최근 30일)
Tommaso Cortopassi
Tommaso Cortopassi 2024년 6월 5일
댓글: Alex 2024년 6월 26일 1:28
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
Tommaso Cortopassi
Tommaso Cortopassi 2024년 6월 6일
@Stephen23 @Torsten yeah, I'll do that. I tried before using a function with a for cycle but for some reasons I got an error in "solve", for not passing enough arguments. Now I tried again and it seems to work. I don't know, for some reason I thought that having a long complicated function handle would have been computationally more efficient than a function with a for cycle, even though I am probably mistaken
Alex
Alex 2024년 6월 26일 1:28
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(:)));

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

제품


릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by