Local function that makes anonymous functions

4 views (last 30 days)
I recently discovered the joy of simulations and the wonder that is ode45. But it got me wondering how to make more dynamic systems as, least with my current methodology I have to write out the ODEs by hand, which for say a 100 particle electron cloud is impracticle. So, I gave myself the task of figuring out just this as a proof of concept, before going on to try some more involved simulations.
The best idea I could come up with is to make a function which spits out a collection of anonymous functions and starting conditions. I think I have it mostly made when I ran into an unexpected problem. It gave me this error.
Unrecognized function or variable 'x'.
I will give you a simplified ecample of what I am trying to do that made the error below as well as the full code in the comments for those interested. I am mostly looking for how to resolve the error, although if there is just a blatantly better way to go about this whole idea that is also welcome. (Honestly why I gave as much preface as I did).
%% Simplified: In this case it would complain about "Unrecognized function or variable 'vals'.
function [odefunc] = funcGen(N)
odefunc = @(t,vals) [];
for i = 1:N
n = 2*(i-1);
recale = vals([n+1,n+2]) / norm(vals([n+1,n+2]));
odefunc(t,vals) = @(t,vals) [odefunc(t,vals);vals(n+1);vals(n+2)];
end
end
  4 Comments
Ameer Hamza
Ameer Hamza on 5 Jun 2020
Edited: Ameer Hamza on 5 Jun 2020
In the simplified example, can you explain what are you trying to do with variable 'recale'? And what do you expect the value of 'val'? Note that 'val' is only defined in the scope of the anonymous function, i.e., only on that line. It does not have any meaning other than that line of code.
Also, how is physConst() defined?
Walter Roberson
Walter Roberson on 5 Jun 2020
odefunc(t,vals) = @(t,vals) [odefunc(t,vals);vals(n+1);vals(n+2)];
You would have to use
odefunc = @(t,vals) [odefunc(t,vals);vals(n+1);vals(n+2)];
At each step you would be shadowing the previous odefunc, "capturing" it inside the anonymous function, so that you would have a chain of anonymous functions that called previous versions of the anonymous function, and it's turtles all the way down to the original [] version. This is permitted, but it is difficult to debug, and it is inefficient. It does not build up a single anonymous function that creates all of the elements in a single step: it would be function calling function calling function... etc., until you got to the [] .

Sign in to comment.

Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!