Customize output of MATLAB's spectrogram function

420 views Asked by At

I would like to know whether it is possible to customize the plot generated by MATLAB's spectrogram function in such a way that its x-axis does not represent the time but another physical signal y2captured simultaneously with the input signal y1 (used for computing the spectrogram). Therefore, it can be assumed that y1 and y2 have the same timestamps as x-axis as in the following example.

N = 1024;
n = 0:N-1;
w0 = 2*pi;
y1 = sin(w0*n);
y2 = n;
spectrogram(y1,'yaxis');
1

There are 1 answers

0
aksadv On

To control the scale of the axes arbitrarily, you could manually plot the spectrogram using imagesc. Here's how:

N = 1024;
n = 0:N-1;
w0 = 2*pi/10;
y1 = sin(w0*n);
y2 = n;

% compute spectrogram
[s,w,t]=spectrogram(y1,'yaxis');

% find values in y2 corresponding to spectrogram time-grid
t2 = interp1((1:N), y2, t);

% use imagesc to plot spectrogram
figure;
imagesc(t2,w/pi,10*log10(abs(s.^2)/length(w)/pi))
set(gca,'YDir','normal');
colorbar;
ylabel('Normalized Frequency (\times \pi rad/sample)');
% caxis([-160, 20]) % manually tweak the color range for best detail

Note that I have made two minor changes to your code:

  1. Changed w0 from 2*pi to 2*pi/10, because the former results in y1 being all zeros.
  2. Changed y2 to be something else than 1:N, which is spectrogram default.

I should also point out that the built-in spectrogram plot does let you control the axes scale in a variety of ways, including specifying the sample rate.