How can I define a function handle with 50 very similar functions?

1 view (last 30 days)
Hello!
I am trying to solve a DDE with ODE45, by rewriting it as a coupled system of ODEs, to do that I need a function handle with i=1...N functions like this f=@u[u(1)-u(2);u(2)-u(3)....;u(N-1)-u(N)] (there are some extra rows in it but those are irrelevant right now).
Is there a way to do this with a foor loop?

Answers (1)

Steven Lord
Steven Lord on 7 Mar 2023
You can't use a for loop in an anonymous function, but the good news is you don't need to. The diff function returns the difference between each element and its predecessor; to get the difference between each element and its successor just multiply by -1.
f = @(x) -diff(x)
f = function_handle with value:
@(x)-diff(x)
x = 1:10;
y = x.^2
y = 1×10
1 4 9 16 25 36 49 64 81 100
differences = f(y)
differences = 1×9
-3 -5 -7 -9 -11 -13 -15 -17 -19
We can spot check by looking at the results for the fifth element:
[y(5)-y(6); differences(5)]
ans = 2×1
-11 -11
Note that differences is one element shorter than y so you'll likely need to add an element at the start or at the end of differences.
g = @(x) [NaN, f(x)]
g = function_handle with value:
@(x)[NaN,f(x)]
[y; g(y)]
ans = 2×10
1 4 9 16 25 36 49 64 81 100 NaN -3 -5 -7 -9 -11 -13 -15 -17 -19

Categories

Find more on Programming 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!