
% Write a Matlab script that removes the exponential broadening from an EMG
% peak of unknown sigma and lambda, by computing the weighted sum of the
% EMG and its first derivative. Start with a weight equal to the FWWM of
% the peak and then adjust the weight iteratively until the resulting peak
% is as narrow as possible without dipping below y=0. EMG peak
% Exponential Broadening Removal from EMG Peak
% This script computes the weighted sum of the EMG and its first derivative
% to remove exponential broadening.

% Create an EMG peak with exponential broadening
t = 0:0.01:10;
sigma = 2;
lambda = 0.5;
emg = exp(-(t-5).^2/(2*sigma^2)) .* exp(-lambda*t);

% Calculate the first derivative of the EMG
derivative = diff(emg);

% Estimate the FWHM of the peak (approximate)
fwhm = 2*sqrt(2*log(2))*sigma;

% Initialize the weight
weight = fwhm;

% Iterate until the peak is as narrow as possible without dipping below zero
while true
    % Add the weighted derivative to the original EMG
    deconvoluted_emg = emg + weight * derivative;

    % Check if the deconvoluted EMG dips below zero
    if min(deconvoluted_emg) < 0
        % If it does, reduce the weight and break the loop
        weight = weight - 0.1;
        break;
    end

    % If it doesn't dip below zero, increase the weight
    weight = weight + 0.1;
end

% Plot the original and deconvoluted EMG signals
figure;
plot(t, emg);
hold on;
plot(t(2:end), deconvoluted_emg);
legend('Original EMG', 'Deconvoluted EMG');
xlabel('Time');
ylabel('Amplitude');
title('EMG Deconvolution');