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!