Help me generate better spectrogram data using Matlab?

13 views (last 30 days)
Hi everyone
I am trying to generate spectrograms for .mat EEG files to show the breakdown of frequencies over time. I have got a series of spectrograms that look like this but I am not sure how to alter the code so they are more useful. My code currently is this:
% Set the directory containing .mat files
dataDir = 'C:\Users\clloy\Downloads\spectrogram_data_to_use';
% Get a list of all .mat files in the directory
matFiles = dir(fullfile(dataDir, '*.mat'));
% Electrode information (modify as per your electrode configuration)
electrodes = 1:32; % Assuming electrodes are labeled from 1 to 32
% Loop through each file and generate spectrograms for each electrode
for k = 1:length(matFiles)
% Load the .mat file
matFilePath = fullfile(dataDir, matFiles(k).name);
dataStruct = load(matFilePath);
% Extract the Clean_data variable
if isfield(dataStruct, 'Clean_data')
Clean_data = dataStruct.Clean_data;
% Sampling frequency (Hz)
fs = 128; % Sampling rate is 128 Hz
% Size of Clean_data
[numElectrodes, numSamples] = size(Clean_data);
% Loop through each electrode and generate spectrogram
for elecIdx = 1:numElectrodes
% Get data for current electrode
electrodeData = Clean_data(elecIdx, :);
% Generate spectrogram
figure;
spectrogram(electrodeData, 256, [], [], fs, 'yaxis');
% Add title and labels
title(['Spectrogram of Electrode ', num2str(elecIdx), ' - File: ', matFiles(k).name]);
xlabel('Time (s)');
ylabel('Frequency (Hz)');
% Customize y-axis labels for electrodes
ax = gca;
ax.YTickLabel = compose('%.1f', ax.YTick);
% Save the figure as an image file
saveas(gcf, fullfile(dataDir, [matFiles(k).name, '_electrode_', num2str(elecIdx), '_spectrogram.png']));
% Close the figure to avoid excessive memory usage
close(gcf);
end
else
warning('File %s does not contain the variable "Clean_data". Skipping...', matFiles(k).name);
continue;
end
end
Please let me know if theres anything I can do to alter it and make the spectrograms better!

Answers (1)

Divyanshu
Divyanshu on 7 Aug 2024
Edited: Divyanshu on 7 Aug 2024
In order to make the spectrograms better, you can make use of certain options of 'spectrogram()' function like 'windowSize','noverlap'.
You can read more about these options in the following documentation link:
Hope it helps!

Categories

Find more on EEG/MEG/ECoG in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!