How to keep both readability and calculation speed when using anonymous functions?
2 views (last 30 days)
Show older comments
There are some time when I use anonymous functions which include product of other anonymous functions. For example, as two anonymous functions
h_exp1 = @(x)exp(1i.*x);
h_exp2 = @(x)exp(1i.*sqrt(x.^2+A^2));
and their product
h_prod = @(x)(h_exp1(x) .* h_exp2(x));
This expression is inefficient in that the product h_prod call exp function twice and it is slower than
h_prod2 = @(x)exp(1i.*(x+sqrt(x.^2+A^2)));
which call exp function once. There are cases where this consumption of time become dominant if h_prod is called millions of times or more.
Of course, its enough to use h_prod2 where the respective constituents are simple, but it seems to become less readable and less extendable when the formulation is basically not simple.
Are there any methods to cope with this? Please forgive my inexperience of program development.
Thank you.
1 Comment
Answers (1)
Alan Stevens
on 21 Aug 2021
How about something like
hexp = @(x,y) exp(1i*(x+y));
x = ..; % set to whatever is required
y = sqrt(x.^2 + A^2);
h1 = hexp(x,0);
h2 = hexp(0,y);
h3 = hexp(x,y);
0 Comments
See Also
Categories
Find more on Logical 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!