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!