%% Estimate Impulse Response Using MLS Excitation
% Use audioread to read in an impulse response recording. Create a dsp.FrequencyDomainFIRFilter object to perform frequency domain filtering using the known impulse response.

[irKnown,fs] = audioread('ChurchImpulseResponse-16-44p1-mono-5secs.wav');
systemModel = dsp.FrequencyDomainFIRFilter(irKnown');

%
% Create an MLS excitation signal by using the mls function. The MLS excitation signal must be longer than the impulse response. Note that the length of the MLS excitation is extended to the next power of two minus one.

excitation = mls(numel(irKnown)+1);

plot(excitation)
title('Excitation')

%
% Replicate the excitation signal four times to measure the average of three measurements. The recording of the first MLS sequence does include all the impulse response information, so impzest discards it as a warmup run. Pad the excitation signal with zeros to account for the filter latency.

numRuns = 4;
excrep = repmat(excitation,numRuns,1);
excrep = [excrep;zeros(numel(irKnown)+1,1)];

%
% Pass the excitation signal through the known filter and then add noise to model a real-word recording (system response). Cut the delay introduced at the beginning by the filter.

rec = systemModel(excrep);
rec = rec + 0.1*randn(size(rec));

rec = rec(numel(irKnown)+2:end,:);

plot(rec)
title('System Response')

%
% In a real-world scenario, the MLS sequence is played back in the system under test while recording. The recording would be cut so that it begins at the moment the MLS sequence is picked-up and truncated to last the duration of the repeated sequence.
% Pass the excitation signal and the system response to the impzest function to estimate the impulse response. Plot the known impulse response and the simulation of the estimated impulse response for comparison.

irEstimate = impzest(excitation,rec);

samples = 1:numel(irKnown);
plot(samples,irEstimate(samples),'bo', ...
     samples,irKnown(samples),'m.')

legend('Known impulse response','Simulation of estimated impulse response')

%
% Copyright 2018 The MathWorks, Inc.