# sampling a continuous time signal using MATLAB?

I have a continuous time signal $$x(t)=cos(2 πft)$$ where $$0\leq t \leq 2$$.

I want to plot discrete time signal $$x(n)$$ where $$0 \leq n \leq 19$$ for sampling frequency 100 Hz and signal frequency 10 Hz.

My MATLAB code is follow:

clc
clear all
close all
t=0:0.1:2
f=10
x=cos(2*pi*f*t)
subplot(211)
plot(t,x)
n=0:19
fs=100
Ts=0.01
x_a=cos(2*pi*f*n*0.01)
subplot(212)
stem(n,x_a)


Please let me know, am I correct?

• If your signal is 2 seconds long and your sampling rate is 100 Hz, then you need 200 samples to capture it – Hilmar Feb 12 at 18:32
• Your timescale on the first one indicates a 10sps rate, at which rate your 10Hz signal will be aliased to DC. Your second should be OK, but I'd use Ts in the cos function instead of the literal 0.01, and I'd define Ts=1/fs...that way you can change fs and everything follows automagically. – Cristobol Polychronopolis Feb 12 at 19:25
• @Hilmar, how i couldn't understand ?can you please put more detail in your comment? – engr Feb 13 at 5:08

This information can be found other places as well but I will step through it here using MATLAB.

You say your sampling rate is $$100$$ Hz and the signal is $$10$$ Hz. Lets define those along with the sampling period ($$1/100$$ seconds).

sampleRate = 100;
samplePeriod = 1/sampleRate;
signalFreq = 10;


Now you want $$2$$ seconds of this, so define your sampled time vector.

nT = 0:samplePeriod:2;


Now we create the signal, and plot the result.

signal = cos(2*pi*signalFreq*nT);

figure
stem(nT, signal)
grid on
xlabel('Time (sec)')
ylabel('Amplitude')


If you only want to plot $$0 \leq n \leq 19$$, then you may instead set nT = [0:19]*samplePeriod;.

• what will be correct/valid convention?n=0:2 or n=0:19? – engr Feb 13 at 5:10
• n = 0:19; creates a row vector of length 20 so that is what you want. n = 0:2; would only create a length 3 vector so you'd only have 3 samples – Engineer Feb 13 at 11:52