fprintf('Beginning to run %s.m.\n', mfilename);
[PKS,LOCS]= findpeaks(y,'NPeaks',numGaussians);
tActual = table((1:numGaussians)', amplitudes(:), centers(:), sigmas(:), 'VariableNames', {'Number', 'Amplitude', 'Mean', 'Width'});
tActual = sortrows(tActual, 3);
tActual.Number = (1:numGaussians)'
legendStrings = cell(numGaussians, 1);
initialGuesses = [tActual.Mean(:), tActual.Width(:)];
initialGuesses = initialGuesses + 2 * rand(size(initialGuesses))
startingGuesses = reshape(initialGuesses', 1, [])
global c NumTrials TrialError
tFit = reshape(x, 1, []);
options = optimset('TolX', 1e-4, 'MaxFunEvals', 10^12);
options.MaxIter = 100000;
[parameter, fval, flag, output] = fminsearch(@(lambda)(fitgauss(lambda, tFit, y)), startingGuesses, options);
yhat = PlotComponentCurves(x, y, tFit, c, parameter);
meanResidual = mean(abs(y - yhat));
fprintf('The mean of the absolute value of the residuals is %f.\n', meanResidual);
caption = sprintf('Estimation of %d Gaussian Curves that will fit data. Mean Residual = %f.', numGaussians, meanResidual);
title(caption, 'FontSize', fontSize, 'Interpreter', 'none');
estimatedMuSigma = reshape(parameter, 2, [])';
gaussianParameters = [c, estimatedMuSigma];
gaussianParameters = sortrows(gaussianParameters, 2);
tEstimate = table((1:numGaussians)', c(:), estimatedMuSigma(:, 1), estimatedMuSigma(:, 2), 'VariableNames', {'Number', 'Amplitude', 'Mean', 'Width'})
hFigError.Name = 'Errors';
semilogy(TrialError, 'b-');
xlabel('Trial Number', 'FontSize', fontSize)
ylabel('Error', 'FontSize', fontSize)
caption = sprintf('Errors for all %d trials.', length(TrialError));
title(caption, 'FontSize', fontSize, 'Interpreter', 'none');
message = sprintf('Done!\nHere is the result!\nNote: there could be multiple ways\n(multiple sets of Gaussians)\nthat you could achieve the same sum (same test curve).');
fprintf('Done running %s.m.\n', mfilename);
function yhat = PlotComponentCurves(x, y, t, c, parameter)
means = parameter(1 : 2 : end);
widths = parameter(2 : 2 : end);
hFig2.Name = 'Fitted Component Curves';
yhat = zeros(1, length(t));
numGaussians = length(c);
legendStrings = cell(numGaussians + 2, 1);
thisEstimatedCurve = c(k) .* gaussian(t, means(k), widths(k));
plot(x, thisEstimatedCurve, '-', 'LineWidth', 2);
yhat = yhat + thisEstimatedCurve;
legendStrings{k} = sprintf('Estimated Gaussian %d', k);
plot(x, y, 'r-', 'LineWidth', 1)
plot(x, yhat, 'k--', 'LineWidth', 2)
xlabel('X', 'FontSize', fontSize)
ylabel('Y', 'FontSize', fontSize)
caption = sprintf('Estimation of %d Gaussian Curves that will fit data.', numGaussians);
title(caption, 'FontSize', fontSize, 'Interpreter', 'none');
legendStrings{numGaussians+1} = sprintf('Actual original signal');
legendStrings{numGaussians+2} = sprintf('Sum of all %d Gaussians', numGaussians);
xlim(sort([x(1) x(end)]));
hFig2.WindowState = 'maximized';
callStackString = GetCallStack(ME);
errorMessage = sprintf('Error in program %s.\nTraceback (most recent at top):\n%s\nError Message:\n%s', ...
mfilename, callStackString, ME.message);
function theError = fitgauss(lambda, t, y)
global c NumTrials TrialError
A = zeros(length(t), round(length(lambda) / 2));
for j = 1 : length(lambda) / 2
A(:,j) = gaussian(t, lambda(2 * j - 1), lambda(2 * j))';
theError = theError + 1000000;
NumTrials = NumTrials + 1;
TrialError(NumTrials) = theError;
callStackString = GetCallStack(ME);
errorMessage = sprintf('Error in program %s.\nTraceback (most recent at top):\n%s\nError Message:\n%s', ...
mfilename, callStackString, ME.message);
function g = gaussian(x, peakPosition, width)
g = exp(-((x - peakPosition) ./ (0.60056120439323 .* width)) .^ 2);
function callStackString = GetCallStack(errorObject)
theStack = errorObject.stack;
stackLength = length(theStack);
[folder, baseFileName, ext] = fileparts(theStack(1).file);
baseFileName = sprintf('%s%s', baseFileName, ext);
callStackString = sprintf('%s in file %s, in the function %s, at line %d\n', callStackString, baseFileName, theStack(1).name, theStack(1).line);
for k = 1 : length(theStack)-3
[folder, baseFileName, ext] = fileparts(theStack(k).file);
baseFileName = sprintf('%s%s', baseFileName, ext);
callStackString = sprintf('%s in file %s, in the function %s, at line %d\n', callStackString, baseFileName, theStack(k).name, theStack(k).line);
errorMessage = sprintf('Error in program %s.\nTraceback (most recent at top):\nError Message:\n%s', ...
function WarnUser(warningMessage)
fprintf('%s\n', warningMessage);
uiwait(warndlg(warningMessage));
folder = 'C:\Users\Public\Documents\MATLAB Settings';
fullFileName = fullfile(folder, 'Error Log.txt');
fid = fopen(fullFileName, 'at');
fprintf(fid, '\nThe error below occurred on %s.\n%s\n', datestr(now), warningMessage);
fprintf(fid, '-------------------------------------------------------------------------------\n');
message = sprintf('Error in WarnUser():\n%s', ME.message);
fprintf('%s\n', message);
uiwait(warndlg(message));