Reputation: 402
I would like to fit a bimodal normal distribution to data that looks bimodally distributed, such as the example below (plot(x)
):
From the MATLAB docs I thought about using the mle function with a function handle to a mixture of two Gaussians:
@(x,p,mu1,mu2,sigma1,sigma2)p*normpdf(x,mu1,sigma1)+(1-p)*normpdf(x,mu2,sigma2)
However, the mle
function fits to the histogram of x
, while I want an approximation to x
itself. How could I achieve this?
Upvotes: 2
Views: 3642
Reputation: 1
%u can use the function histfit(yourdata,nbins,'Kernel','normal'); %sometimes the it doesnt converge ; in those case u can resort to distributionFitter app distributionFitter(yourdata); %select non-parametric ; then normal
Upvotes: 0
Reputation:
The idea is to create array y
whose histogram looks like your function x
(which should be positive everywhere):
%// Calculate
N = numel(x);
xi = fix(x/max(x)*100); % Limit the memory damage
yp = arrayfun(@(n) n*ones(1,xi(n)), 1:N, 'UniformOutput', false);
y = [yp{:}];
%// Visually inspect
ax = axes('Parent', figure());
plot(ax, xi); hold(ax, 'on');
hist(ax, y, N);
Upvotes: 2
Reputation: 3440
Matlab has a builtin bimodal fit
f =@(A,m,s,x) A(1) * exp(-((x-m(1))/s(1)).^2) + A(2) * exp(-((x-m(2))/s(2)).^2);
g =@(x) f([5, 10], [1, 10], [3, 5], x);
x = (-20:0.01:20)';
y = g(x) + 0.25*(rand(size(x)) - 0.5);
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Display = 'Off';
[fitresult, gof] = fit( x, y, 'gauss2', opts );
plot( fitresult, x, y );
Upvotes: 2