How can I define a function handle with 50 very similar functions?
1 view (last 30 days)
Show older comments
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?
0 Comments
Answers (1)
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)
x = 1:10;
y = x.^2
differences = f(y)
We can spot check by looking at the results for the fifth element:
[y(5)-y(6); differences(5)]
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)]
[y; g(y)]
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!