MATLAB: How to choose Spectrogram parameter

dspfftfrequencyMATLABsignal processingspectrogramstft

I have a signal with 3Hz frequency and runs from 0:10 second. The signal is zeroed everywhere except from 2 to 4 and 7 to 8 second in the signal as per the image below. I tried to to get the spectrogram but it didn't give correct representation and accurate one. When i surf the spectrogram i can see the 3 signal but the time is shifted. How to choose the correct parameters for spectrogram ? My code:
t=0:1/50:10;
x=sin(2*pi*t*3);
x[1:100]=0;
x[200:350]=0;
x[400:501]=0;
[s,ff,tt,p]=spectrogram(x,50,25,2048,50);
surf(tt,ff,(p),'edgecolor','none'); axis tight; view(0,90);
Thank you

Best Answer

Where you set it to zero, you should be using parentheses and not brackets. not really sure what you were plotting since that syntax should just throw an error.
This should create what you would expect to see, two pulses at around 3 Hz
t=0:1/50:10;
x=sin(2*pi*t*3);
x(1:100)=0;
x(200:350)=0;
x(400:501)=0;
[s,ff,tt,p]=spectrogram(x,50,25,2048,50);
surf(tt,ff,(p),'edgecolor','none'); axis tight; view(0,90);