How to average spectrograms?

12 views (last 30 days)
Monserrat SB
Monserrat SB on 14 Dec 2023
Answered: Pratyush on 14 Dec 2023
Hello, I hope you are doing well. I'm a bit stuck with an analysis. I have a matrix of cells (trials (rows) by channels (columns)) that contains signals of different sizes. I need to create the spectrogram for each signal to then obtain the average spectrogram per channel. Does anyone have any ideas?

Accepted Answer

Pratyush
Pratyush on 14 Dec 2023
Hi Monserrat,
I understand that you want to create a spectrograms for a set of signals and then average them in MATLAB.
You could follow these steps:
  1. You'll need to initialize variables to store the cumulative spectrogram data for each channel.
  2. Loop through each trial and channel, calculate the spectrogram for each signal, and add it to the cumulative spectrogram for the corresponding channel.
  3. After accumulating the spectrogram data, average it by the number of trials for each channel.
Here's a sample code to demonstrate this:
% Assuming 'data' is your cell matrix with dimensions trials x channels
[numTrials, numChannels] = size(data);
% Parameters for the spectrogram (you might need to adjust these)
windowSize = 256; % Window size for the spectrogram
noverlap = 128; % Overlap between windows
nfft = 512; % Number of FFT points
% Initialize a cell array to store cumulative spectrograms for each channel
cumulativeSpectrograms = cell(1, numChannels);
% Loop through each trial and channel
for chan = 1:numChannels
% Initialize cumulative spectrogram for the current channel
cumulativeSpectrograms{chan} = [];
for trial = 1:numTrials
% Get the signal for the current trial and channel
signal = data{trial, chan};
% Calculate the spectrogram for the current signal
[S, F, T, P] = spectrogram(signal, windowSize, noverlap, nfft, 'yaxis');
% If this is the first trial, initialize the cumulative spectrogram matrix
if trial == 1
cumulativeSpectrograms{chan} = zeros(size(P));
end
% Add the power spectral density to the cumulative spectrogram
cumulativeSpectrograms{chan} = cumulativeSpectrograms{chan} + P;
end
% Average the cumulative spectrogram by the number of trials
cumulativeSpectrograms{chan} = cumulativeSpectrograms{chan} / numTrials;
end
% 'cumulativeSpectrograms' now contains the average spectrogram for each channel
Adjust the 'windowSize', 'noverlap', and 'nfft' parameters based on the sampling rate of your signals and the frequency resolution you desire.
If your signals have different lengths, you may need to pad them to the same length before averaging the spectrograms.

More Answers (0)

Categories

Find more on Time-Frequency Analysis in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!