how to recalibrate two curves in time? - matlab

I am currently processing EMG signals obtained on a bicep curl exercise under different conditions. At the end of my code I replace the normalized signals of each condition and that as a function of time. my problem is that during this superposition peaks puffs are shifted in time from one curve to another because the participants did not start at the same time its exercise and I'd like to "recalibrate" (I do not I'm not sure this is the right word of the shot) the curves in time for each contraction to start and finish at the same time (on the blue curve there is a contraction of more at the end)
this is what my code looks like for now
%% Process EMG dynamique
clc, clear all, close all
%% Haltère 10 Kg
%% Filtrage, centrage et rectication du signal
data_EMG = load([''10kg_haltere-Philippe.txt'']); % Load file EMG
fe_EMG = 1000; % sampling frequency Acceleration Hz
timeEMG_10 = (0:1/fe_EMG:(length(data_EMG)-1)*(1/fe_EMG))'; % Time vector
for m = 1 : 2
[B,A] = butter(8/2,[15*1.247 400*1.247]/(fe_EMG/2),'bandpass'); % filter butterworth band pass 20 à 400 Hz d'ordre 4
data_EMG_filt = filtfilt(B,A,data_EMG(:,m)); % filtring pass band
data_EMG_filt_1 = data_EMG_filt - ones(length(data_EMG_filt),1)*mean(data_EMG_filt); %Centering of the EMG signal around the individual mean of each muscle
data_EMG_filt_rectified = abs(data_EMG_filt_1); % Rectification of the EMG signal = Full wave rectification
%% courbe RMS/EMG
rms_window = 1300;
for i = (rms_window/2)+1 : length(data_EMG)-(rms_window/2)
rms_data_EMG(i) = rms(data_EMG_filt_rectified([i-(rms_window/2):i+(rms_window/2)]));
end
[B,A] = butter(4/2,[5*1.247]/(fe_EMG/2),'low'); % filter butterworth band pass 20 à 400 Hz d'ordre 4
data_EMG_filt_rectified_filtbutter = filtfilt(B,A,data_EMG_filt_rectified); % filtring pass band
EMG_max = max(data_EMG_filt_rectified_filtbutter);
data_EMG_filt_rectified_filtbutter_norm_10 = (data_EMG_filt_rectified_filtbutter.*100)./EMG_max;
% Stockage
RMS(:,m) = rms_data_EMG;
EMG_filt(:,m) = data_EMG_filt_rectified;
EMG_filtbutter(:,m) = data_EMG_filt_rectified_filtbutter;
EMG_filtbutter_norm(:,m) = data_EMG_filt_rectified_filtbutter_norm_10;
end
%% Haltère 5 kg
%% Filtrage, centrage et rectication du signal
data_EMG = load(['5kg_haltere-Philippe.txt']); % Load file EMG
fe_EMG = 1000; % sampling frequency Acceleration Hz
timeEMG_5 = (0:1/fe_EMG:(length(data_EMG)-1)*(1/fe_EMG))'; % Time vector
for m = 1 : 2
[B,A] = butter(4/2,[15*1.247 400*1.247]/(fe_EMG/2),'bandpass'); % filter butterworth band pass 20 à 400 Hz d'ordre 4
data_EMG_filt = filtfilt(B,A,data_EMG(:,m)); % filtring pass band
data_EMG_filt_1 = data_EMG_filt - ones(length(data_EMG_filt),1)*mean(data_EMG_filt); %Centering of the EMG signal around the individual mean of each muscle
data_EMG_filt_rectified = abs(data_EMG_filt_1); % Rectification of the EMG signal = Full wave rectification
%% courbe RMS/EMG
rms_window = 1300;
for i = (rms_window/2)+1 : length(data_EMG)-(rms_window/2)
rms_data_EMG(i) = rms(data_EMG_filt_rectified([i-(rms_window/2):i+(rms_window/2)]));
end
% Application d'un deuxième filtre (pour analyser les bouffé EMG) à la place de lp filter
[B,A] = butter(8/2,[5*1.247]/(fe_EMG/2),'low');
data_EMG_filt_rectified_filtbutter = filtfilt(B,A,data_EMG_filt_rectified);
EMG_max = max(data_EMG_filt_rectified_filtbutter);
data_EMG_filt_rectified_filtbutter_norm_5 = (data_EMG_filt_rectified_filtbutter.*100)./EMG_max;
% Stockage
RMS(:,m) = rms_data_EMG;
EMG_filt(:,m) = data_EMG_filt_rectified;
EMG_filtbutter(:,m) = data_EMG_filt_rectified_filtbutter;
EMG_filtbutter_norm_5(:,m) = data_EMG_filt_rectified_filtbutter_norm_5;
end
figure
plot(timeEMG_10,EMG_filtbutter_norm(:,1))
hold on
plot(timeEMG_5,data_EMG_filt_rectified_filtbutter_norm_5)
hold off
Link to data

I made up my own function for something similar. I am sure there are probably better ways to do this however it works most of the time. The basic ideas is to shift one of the lines 1 point at a time (limited to some +/- range) and check the RMSE between the 2. Record where the lowest RMSE occurs and that is how far you should shift.
Time aligning function:
function [time2] = dataSync(data1, data2, time2, maxShift)
minError = inf;
shiftPoint = NaN;
for ii = -maxShift:maxShift
if ii <= 0 %Shift data 2 to the left
RMSE = sqrt(mean((data1(1:end+ii) - data2(1-ii:end)).^2));
else %Shift data 2 to the right (...or data 1 left)
RMSE = sqrt(mean((data1(1+ii:end) - data2(1:end-ii)).^2));
end
if RMSE < minError
minError = RMSE;
shiftPoint = ii;
end
end
if shiftPoint ~= 0
time2 = time2 + time2(abs(shiftPoint))*sign(shiftPoint);
end
Putting it in your code:
Note that I limited the shift to +/- 5000 samples.
figure
plot(timeEMG_10,EMG_filtbutter_norm(:,1))
hold on
%% Try to line up the times.
[timeSync] = dataSync(EMG_filtbutter_norm(:,1), data_EMG_filt_rectified_filtbutter_norm_5, timeEMG_5, 5000);
% plot(timeEMG_5,data_EMG_filt_rectified_filtbutter_norm_5)
% hold off
plot(timeSync,data_EMG_filt_rectified_filtbutter_norm_5,'g')
hold off
Gives a lined up plot that
Used to be:
And now is:
Note that you don't have the same number of peaks but that is probably the best that you can do. Also there is the assumption that the 2 data arrays have the same number of elements, same original time vectors, etc. which might not always be true.

Related

Findpeaks in Spectrum Matalb

I am trying to find peaks in spectrum but I need to extract only peak of base frequency and its harmonics, red rectangular. How to exclude anything before base frequency and only include base frequency and its 3 harmonics. I use this code but it does not help. Any idea?
pks = findpeaks(q);
findpeaks(q,'MinPeakDistance',99)
%findpeaks(q,'MinPeakHeight',0.0004)
xlim([0.1 500])
When using:
Fs = 1000;
t = 0:0.001:1-0.001; % 250-Hz sine wave modulated at 100 Hz
x = [1+cos(2*pi*100*t)].*cos(2*pi*250*t);
%envspectrum(x,Fs)
[ES,F]=envspectrum(x,Fs);
%%
findpeaks(ES,F)
% Now for only > 99 Hz (choose the freq you fancy)
idx = F >= 99; % greater than 99 Hz
findpeaks(ES(idx),F(idx)) % idx only select those F > 99
% Good? Keep the values of amplitud and location (in frequencies) of the ES
[pks,loc] = findpeaks(ES(idx),F(idx));
% If you just want to have the first 5 peaks (or the n? you choose):
% Select only 3 first.
if length(pks) > 3 % Check you didnt get less peaks
pks = pks(1:3);
loc = loc(1:3);
end
% To plot the peaks in the envelope
plot(F(idx),ES(idx),loc,pks,'r*')
I get this:
And this as result:
EDITED to adapt to new code with an example. We are applying on the envelope spectrum of a signal - [ES,F] = envspectrum(sig,Fs);-, so we know the signal and its frequency sampling (fs).
Still being the same process. You can just compute the values in findpeaks() for only those samples of your signal which are higher than 250 Hz. For that purpose, you define a logical array for the frequencies values you want to:
idx = F >= 250; % 250 Hz
And apply this logical index to the envelop spectrum of your signal and frequencies where you want to apply the function findpeaks():
[pks,loc] = findpeaks(ES(idx),F(idx));
Example:
% Let's create a signal with fs = 2500 Hz
% This is just to create an example, don't worry about these lines
fs = 2500;
f0 = 25;
n = 8;
d = 0.02;
p = 0.12;
t = 0:1/fs:1-1/fs;
z = [1 0.5 0.2 0.1 0.05]*sin(2*pi*f0*[1 2 3 4 5]'.*t)/5;
% z: our signal
% t: time array of the signal (to plot)
% How does the signal look?
plot(t,z)
% Calculating the envelope signal and its spectrum
[ES,F]=envspectrum(z,fs);
% Plot the envelop if you want:
envspectrum(z,fs)
% ES: Envelope spectrum of the signal
% F: array of frequencies used for the spectrum (half our fs for Nyquist Theorem)
% Find the peaks of the envelope spectrum
% Let's see how it is for all the envelope
findpeaks(ES,F)
% Now for only > 250 Hz (choose the freq you fancy)
idx = F >= 250; % greater than 250 Hz
findpeaks(ES(idx),F(idx)) % idx only select those F > 250
% Good? Keep the values of amplitud and location (in frequencies) of the ES
% Use 'NPeaks' input to tell function to select only 5 first peaks it can find.
[pks,loc] = findpeaks(ES(idx),F(idx), 'NPeaks', 5);
% To plot the peaks in the envelope
plot(F(idx),ES(idx),loc,pks,'r*')
% Note in this example the first peak (in 250 Hz) is not selected
% because is not a local maximum when we narrow the envelope.
% If the function select false peaks somehow, you can use
%'MinPeakHeight' to specify an absolute amplitude, 'MinPeakProminence '
%for a relative amplitude or 'Threshold' inputs for a better fit.
https://uk.mathworks.com/matlabcentral/answers/768537-use-findpeaks-on-specific-frequency-range
https://uk.mathworks.com/help/signal/ref/findpeaks.html#responsive_offcanvas

Morlet wavelet transformation function returns nonsensical plot

I have written a matlab function (Version 7.10.0.499 (R2010a)) to evaluate incoming FT signal and calculate the morlet wavelet for the signal. I have a similar program, but I needed to make it more readable and closer to mathematical lingo. The output plot is supposed to be a 2D plot with colour showing the intensity of the frequencies. My plot seems to have all frequencies the same per time. The program does make an fft per row of time for each frequency, so I suppose another way to look at it is that the same line repeats itself per step in my for loop. The issue is I have checked with the original program, which does return the correct plot, and I cannot locate any difference beyond what I named the values and how I organized the code.
function[msg] = mile01_wlt(FT_y, f_mn, f_mx, K, N, F_s)
%{
Fucntion to perform a full wlt of a morlet wavelett.
optimization of the number of frequencies to be included.
FT_y satisfies the FT(x) of 1 envelope and is our ft signal.
f min and max enter into the analysis and are decided from
the f-image for optimal values.
While performing the transformation there are different scalings
on the resulting "intensity".
Plot is made with a 2D array and a colour code for intensity.
version 05.05.2016
%}
%--------------------------------------------------------------%
%{
tableofcontents:
1: determining nr. of analysis f, prints and readies f's to be used.
2: ensuring correct orientation of FT_y
3:defining arrays
4: declaring waveletdiagram and storage of frequencies
5: for-loop over all frequencies:
6: reducing file to manageable size by truncating time.
7: marking plot to highlight ("randproblemer")
8: plotting waveletdiagram
%}
%--------------------------------------------------------------%
%1: determining nr. of analysis f, prints and readies f's to be used.
DF = floor( log(f_mx/f_mn) / log(1+( 1/(8*K) ) ) ) + 1;% f-spectre analysed
nr_f_analysed = DF %output to commandline
f_step = (f_mx/f_mn)^(1/(DF-1)); % multiplicative step for new f_a
f_a = f_mn; %[Hz] frequency of analysis
T = N/F_s; %[s] total time sampled
C = 2.0; % factor to scale Psi
%--------------------------------------------------------------%
%2: ensuring correct orientation of FT_y
siz = size(FT_y);
if (siz(2)>siz(1))
FT_y = transpose(FT_y);
end;
%--------------------------------------------------------------%
%3:defining arrays
t = linspace(0, T*(N-1)/N, N); %[s] timespan
f = linspace(0, F_s*(N-1)/N, N); %[Hz] f-specter
%--------------------------------------------------------------%
%4: declaring waveletdiagram and storage of frequencies
WLd = zeros(DF,N); % matrix of DF rows and N columns for storing our wlt
f_store = zeros(1,DF); % horizontal array for storing DF frequencies
%--------------------------------------------------------------%
%5: for-loop over all frequencies:
for jj = 1:DF
o = (K/f_a)*(K/f_a); %factor sigma
Psi = exp(- 0*(f-f_a).*(f-f_a)); % FT(\psi) for 1 envelope
Psi = Psi - exp(-K*K)*exp(- o*(f.*f)); % correctional element
Psi = C*Psi; %factor. not set in stone
%next step fits 1 row in the WLd (3 alternatives)
%WLd(jj,:) = abs(ifft(Psi.*transpose(FT_y)));
WLd(jj,:) = sqrt(abs(ifft(Psi.*transpose(FT_y))));
%WLd(jj,:) = sqrt(abs(ifft(Psi.*FT_y))); %for different array sizes
%and emphasizes weaker parts.
%prep for next round
f_store (jj) = f_a; % storing used frequencies
f_a = f_a*f_step; % determines the next step
end;
%--------------------------------------------------------------%
%6: reducing file to manageable size by truncating time.
P = floor( (K*F_s) / (24*f_mx) );%24 not set in stone
using_every_P_point = P %printout to cmdline for monitoring
N_P = floor(N/P);
points_in_time = N_P %printout to cmdline for monitoring
% truncating WLd and time
WLd2 = zeros(DF,N_P);
for jj = 1:DF
for ii = 1:N_P
WLd2(jj,ii) = WLd(jj,ii*P);
end
end
t_P = zeros(1,N_P);
for ii = 1:N_P % set outside the initial loop to reduce redundancy
t_P(ii) = t(ii*P);
end
%--------------------------------------------------------------%
%7: marking plot to highlight boundary value problems
maxval = max(WLd2);%setting an intensity
mxv = max(maxval);
% marks in wl matrix
for jj= 1:DF
m = floor( K*F_s / (P*pi*f_store(jj)) ); %finding edges of envelope
WLd2(jj,m) = mxv/2; % lower limit
WLd2(jj,N_P-m) = mxv/2;% upper limit
end
%--------------------------------------------------------------%
%8: plotting waveletdiagram
figure;
imagesc(t_P, log10(f_store), WLd2, 'Ydata', [1 size(WLd2,1)]);
set(gca, 'Ydir', 'normal');
xlabel('Time [s]');
ylabel('log10(frequency [Hz])');
%title('wavelet power spectrum'); % for non-sqrt inensities
title('sqrt(wavelet power spectrum)'); %when calculating using sqrt
colorbar('location', 'southoutside');
msg = 'done.';
There are no error message, so I am uncertain what exactly I am doing wrong.
Hope I followed all the guidelines. Otherwise, I apologize.
edit:
my calling program:
% establishing parameters
N = 2^(16); % | number of points to sample
F_s = 3.2e6; % Hz | samplings frequency
T_t = N/F_s; % s | length in seconds of sample time
f_c = 2.0e5; % Hz | carrying wave frequency
f_m = 8./T_t; % Hz | modulating wave frequency
w_c = 2pif_c; % Hz | angular frequency("omega") of carrying wave
w_m = 2pif_m; % Hz | angular frequency("omega") of modulating wave
% establishing parameter arrays
t = linspace(0, T_t, N);
% function variables
T_h = 2*f_m.*t; % dimless | 1/2 of the period for square signal
% combined carry and modulated wave
% y(t) eq. 1):
y_t = 0.5.*cos(w_c.*t).*(1+cos(w_m.*t));
% y(t) eq. 2):
% y_t = 0.5.*cos(w_c.*t)+0.25*cos((w_c+w_m).*t)+0.25*cos((w_c-w_m).*t);
%square wave
sq_t = cos(w_c.*t).*(1 - mod(floor(t./T_h), 2)); % sq(t)
% the following can be exchanged between sq(t) and y(t)
plot(t, y_t)
% plot(t, sq_t)
xlabel('time [s]');
ylabel('signal amplitude');
title('plot of harmonically modulated signal with carrying wave');
% title('plot of square modulated signal with carrying wave');
figure()
hold on
% Fourier transform and plot of freq-image
FT_y = mile01_fftplot(y_t, N, F_s);
% FT_sq = mile01_fftplot(sq_t, N, F_s);
% Morlet wavelet transform and plot of WLdiagram
%determining K, check t-image
K_h = 57*4; % approximation based on 1/4 of an envelope, harmonious
%determining f min and max, from f-image
f_m = 1.995e5; % minimum frequency. chosen to showcase all relevant f
f_M = 2.005e5; % maximum frequency. chosen to showcase all relevant f
%calling wlt function.
name = 'mile'
msg = mile01_wlt(FT_y, f_m, f_M, K_h, N, F_s)
siz = size(FT_y);
if (siz(2)>siz(1))
FT_y = transpose(FT_y);
end;
name = 'arnt'
msg = arnt_wltransf(FT_y, f_m, f_M, K_h, N, F_s)
The time image has a constant frequency, but the amplitude oscillates resempling a gaussian curve. My code returns a sharply segmented image over time, where each point in time holds only 1 frequency. It should reflect a change in intensity across the spectra over time.
hope that helps and thanks!
I found the error. There is a 0 rather than an o in the first instance of Psi. Thinking I'll maybe rename the value as sig or something. besides this the code works. sorry for the trouble there

Matlab : What is the BER performance of Constant Modulus Algorithm and issue in filter function

I need help in plotting the Bit error curve or the symbol error curve for BPSK modulation scheme for varying Signal to Noise ratios or Eb/N0. The plot should show the simulated versus the theoretical curve, but I cannot figure out how to mitigate the problems when using the Constant Modulus Algorithm as an Equalizer which are:
(1)
Error using *
Inner matrix dimensions must agree.
Error in BER_BPSK_CMA (line 50)
yy = w'*x;
(2) I want to use the filter function instead of conv in order to model a moving average channel model, chanOut = filter(ht,1,s). But, when I use filter, I am getting an error. How can I use filter function here?
(3) Bit error rate calculation
UPDATED Code with the Problem 1 solved. However, I am still unable to use filter and unsure if BER curve is proper or not.
Below is the code I wrote:
% Script for computing the BER for BPSK modulation in 3 tap ISI
% channel
clear
N = 10^2; % number of bits or symbols
Eb_N0_dB = [0:15]; % multiple Eb/N0 values
K = 3; %number of users
nTap = 3;
mu = 0.001;
ht = [0.2 0.9 0.3];
L = length(ht);
for ii = 1:length(Eb_N0_dB)
% Transmitter
ip = rand(1,N)>0.5; % generating 0,1 with equal probability
s = 2*ip-1; % BPSK modulation 0 -> -1; 1 -> 0
% Channel model, multipath channel
chanOut = conv(s,ht);
% chanOut = filter(ht,1,s); %MA
n = 1/sqrt(2)*[randn(1,N+length(ht)-1) + j*randn(1,N+length(ht)-1)]; % white gaussian noise, 0dB variance
% Noise addition
y = chanOut + 10^(-Eb_N0_dB(ii)/20)*n; % additive white gaussian noise
%CMA
Le =20; %Equalizer length
e = zeros(N,1); % error
w = zeros(Le,1); % equalizer coefficients
w(Le)=1; % actual filter taps are flipud(w)!
yd = zeros(N,1);
r = y';
% while(1)
for i = 1:N-Le,
x = r(i:Le+i-1);
%x = r(i:(Le+i-1));
yy = w'*x;
yd(i)= yy;
e(i) = yy^2 - 1;
mse_signal(ii,i) = mean(e.*e);
w = w - mu * e(i) * yy * x;
end
sb=w'*x; % estimate symbols (perform equalization)
% receiver - hard decision decoding
ipHat = real(sb)>0;
% counting the errors
nErr_CMA(ii) = size(find([ip- ipHat]),2);
% calculate SER
end
simBer_CMA = nErr_CMA/N;
theoryBer = 0.5*erfc(sqrt(10.^(Eb_N0_dB/10))); % theoretical ber
for i=1:length(Eb_N0_dB),
tmp=10.^(i/10);
tmp=sqrt(tmp);
theoryBer(i)=0.5*erfc(tmp);
end
figure
semilogy(theoryBer,'b'),grid;
hold on;
semilogy(Eb_N0_dB,simBer_CMA,'r-','Linewidth',2);
%axis([0 14 10^-5 0.5])
grid on
legend('sim-CMA');
xlabel('Eb/No, dB');
ylabel('Bit Error Rate');
title('Bit error probability curve for BPSK in ISI with CMA equalizer');
There's an error in these three lines:
sb=w'*x; % estimate symbols (perform equalization)
% receiver - hard decision decoding
ipHat = real(sb)>0;
they worked inside the while loop but you are now performing a post-estimation, so the correct lines are:
sb=conv(w,y); % estimate symbols (perform equalization)
% receiver - hard decision decoding
ipHat = real(sb(Le+1:end-1))>0; % account for the filter delay
There is still some issue with the output... but I can't go further in the analisys.
Your first problem is easily solved: change the line to
x = y(i:(Le+i-1));
Your call of filter looks OK. Which error do you get?
Maybe this is a place to start looking.
Or here (would Fig. 4 be the type of plot you're after?)

Get Exact Frequency From Digital Signal

I studies on Digital Signal Filtering and I have a file includes some signal data. I wrote Matlab Program to get 23 to 27 Hz from original signal. but filtered signal is different. my desire filter is bandpass but my code work like low pass filter.
this is my code :
clc;
clear all;
load('SignalFile.mat');
%number of sample
SampleNumber = 60000;
%create hamming window
hamm = hamming((SampleNumber))'; %'
% there is 4 data in SignalFile.mat
for pl=1:4
% get name of data in signalFile.mat
data = eval(['mydata' num2str(pl)]);
[n,c] = size(data);
nk=SampleNumber;
% there is 2 signal in each data. but main signal exists on data(1:nk,1);
% nk is Sample Number.
mydata = data(1:nk,1) ;
encodedata = data(1:nk,2);
% Sample Rate my this file equal to data length / 4 ->> ~ 39000 sample
% per second.
fs = floor(n/4); % Sampling rate [Hz]
noSamples = nk; % Number of samples
f = 0 : fs/noSamples : fs - fs/noSamples; % Frequency vector
figure;
subplot(2,2,1);
plot(mydata);
x_fft = abs(fft(mydata));
subplot(2,2,2);
plot(f,x_fft);
xlim([1 100]);
centerf = 25; % 25 Hz Center
bw=2; %Bandwisth
fc=pi*centerf; %Center Frequency
L = nk; %sample number;
%Compute Filter
hsuup=(-(L-1)/2:(L-1)/2);
hideal1=hamm.*(2*(fc+bw)*(sin(2*(fc+bw)*hsuup/fs)./(2*(2*fc+bw)*hsuup/fs)));
hideal2=hamm.*(2*(fc-bw)*(sin(2*(fc-bw)*hsuup/fs)./(2*(2*fc+bw)*hsuup/fs)));
h_bpf=(hideal1-hideal2);
% transform mydata to Ferequency Domain
comp_sig_fft=fft(mydata)'; %'
% transform Filter Windows to Ferequency Domain
h_bpf_fft=fft(h_bpf);
% Filter Signal
s_fft=comp_sig_fft.*h_bpf_fft;
%
band_passed_signal=real(ifft(s_fft));
subplot(2,2,3);
plot(band_passed_signal);
x_fft = abs(fft(band_passed_signal));
subplot(2,2,4);
plot(f,x_fft);
xlim([1 100]);
end
is there any idea?
best regards.
my datafile uploaded here :
http://wikisend.com/download/574638/SignalFile.mat
result Images :
https://www.imageupload.co.uk/image/ZLzM
if you look at image, you can find under 20hz signal exists in filtered signal yet.

Matlab fft function

The code below is from the Matlab 2011a help about fft function.
I think there is a problem here : why do they multiply t(1:50) by Fs, and then say it's time in millisecond ? Certainly, it happens to be true in this very particular case, but change the value of Fs to, say, 2000, and it won't work anymore, obviously because of this factor of 2. Right ? Quite misleading, isn't it ? What do I miss ?
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sample time
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
% Sum of a 50 Hz sinusoid and a 120 Hz sinusoid
x = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
y = x + 2*randn(size(t)); % Sinusoids plus noise
plot(Fs*t(1:50),y(1:50))
title('Signal Corrupted with Zero-Mean Random Noise')
xlabel('time (milliseconds)')
Clearer with this :
fs = 2000; % Sampling frequency
T = 1 / fs; % Sample time
L = 1000; % Length of signal
t2 = (0:L-1)*T; % Time vector
f = 50; % signal frequency
s2 = sin(2*pi*f*t2);
figure, plot(fs*t2(1:50),s2(1:50)); % NOT good
figure, plot(t2(1:50),s2(1:50)); % good
You don't miss anything. This is a typical bad practice of not having units as comments for each line. For example,
Fs=1000; % in [Hz]
T=1/Fs; % [sec]
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
then, the time vector has units of 1/1000 seconds, or milliseconds... (each element is 1 ms).
In the other case Fs=2000 %[Hz], which makes the time vector to have units of 1/2000 seconds...