function [positions, widths, heights] = iterativefitGaussians(x, y, n, initPositions, initWidths)
% ChatGPT: Fit n Gaussian functions to the data given in x and y
%   [positions,widths,heights]=fitGaussians(x,y,n,initPositions,initWidths)
%   fits the sum of n Gaussian functions to the data given in x and y. The
%   initial estimates of the positions and widths of the Gaussians are given
%   in the vectors initPositions and initWidths. The function returns the
%   position, width, and height of all the Gaussians.

% Initialize variables
positions = initPositions;
widths = initWidths;
heights = zeros(1, n);

% Set optimization options
options = optimoptions('lsqcurvefit', 'Display', 'off');

% Fit the Gaussians
for i = 1:n
    % Define the function to fit
    fitFcn = @(p, x) p(1) .* exp(-((x - p(2))./p(3)).^2);
    
    % Define the initial values of the parameters
    initParams = [y(i), positions(i), widths(i)];
    
    % Define the parameter bounds
    lb = [0, min(x), 0];
    ub = [inf, max(x), inf];
    
    % Fit the Gaussian
    params = lsqcurvefit(fitFcn, initParams, x, y, lb, ub, options);
    
    % Extract the position, width, and height of the Gaussian
    positions(i) = params(2);
    widths(i) = params(3);
    heights(i) = params(1);
end
end
