How to keep both readability and calculation speed when using anonymous functions?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Alan Stevens
2021-8-21
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!