Generic Anonymous Function Setup

조회 수: 1 (최근 30일)
dsmalenb
dsmalenb 2018년 7월 26일
댓글: dsmalenb 2018년 7월 26일
Hello!
I was wondering if the following is possible using anonymous functions. I am fairly new to them and this is not for a class - just FYI.
Let N >= 2 specify the number of mixture components I would like to build into my anonymous function. Let's say I want each component to be a Normal Distribution. I have three vectors for their weights (w), means (m), and standard deviations (s).
If N = 2 then the anonymous function would look like:
fun = @(x) w(1)/(s(1) *sqrt(2*pi))*exp(-(x-m(1))^2/(2*s(1)^2)) + w(2)/(s(2) *sqrt(2*pi))*exp(-(x-m(2))^2/(2*s(2)^2));
This becomes exceedingly arduous as N grows. It would be preferable to be able to define this function generically so it does not have to get written out.
Is this possible? From research the literature I am only finding examples where the author "hard coded" the function.
However, I could be searching for it incorrectly or missing a specific term.
Any insights would be greatly appreciated.

채택된 답변

Stephen23
Stephen23 2018년 7월 26일
편집: Stephen23 2018년 7월 26일
Learn how to write vectorized code, then your task is easy!
Your function:
>> w = 1:2;
>> m = 2:3;
>> s = 3:4;
>> fun = @(x) w(1)/(s(1)*sqrt(2*pi))*exp(-(x-m(1))^2/(2*s(1)^2)) + w(2)/(s(2)*sqrt(2*pi))*exp(-(x-m(2))^2/(2*s(2)^2));
>> fun(1)
ans = 0.30183
Vectorized function (simpler):
>> foo = @(x)sum(w./(s.*sqrt(2*pi)).*exp(-(x-m).^2./(2*s.^2)));
>> foo(1)
ans = 0.30183
Vectorized function, with N==4:
>> w = 0:3;
>> m = 3:6;
>> s = 6:9;
>> foo = @(x)sum(w./(s.*sqrt(2*pi)).*exp(-(x-m).^2./(2*s.^2)));
>> foo(1)
ans = 0.25397
When you write vectorized code you can give it arrays of any size and it will work. Any time you find yourself copy-and-pasting code then you are doing something wrong.
  댓글 수: 1
dsmalenb
dsmalenb 2018년 7월 26일
Not all heroes wear capes I see. Thank you.
Been programming since '90. Old habits take some time to unlearn!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2016b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by