user466534
user466534

Reputation:

generate 100 sample at given rate

i want to generate 100 samples of sinusoid in matlab with frequency 0.2Hz and sampling rate 2Hz. ,for this i used following code

f=0.2;
 fs=2;
 A=100;%suppose that amplitude is 100
 q=20;
 t=0:1/fs:50;
 x=A*sin(2*pi*f*t+q);

but length of x is 101,not 100;so what would be correct form for generate exactly 100 sample data?i have calculated approximately what should be upper limit to get sample data with size 100;for this i have chose 50;but is there any other method for this?of course i can calculate period

T=1/f=5;

but how can i use it?should i multiply it by fs or vice versa fs should be divided by period?

Upvotes: 2

Views: 243

Answers (2)

horchler
horchler

Reputation: 18504

You can try the linspace function, i.e.:

number_of_sample_data = 100;
f = 0.2;
fs=2;
A=100;%suppose that amplitude is 100
q=20;
tf=number_of_sample_data/fs; %final time
t=linspace(0,tf,number_of_sample_data);
x=A*sin(2*pi*f*t+q);

Note, however, that linspace will not always give exactly the same numeric values as @Franck Dernoncourt's more efficient solution. This is because some numbers cannot be represented exactly in floating point and linspace builds the vector slightly differently. Type edit linspace to see how. For the particular values you gave, @Franck Dernoncourt's solution is both more efficient and more precise because 1/fs=0.5 can be represented exactly in floating point.

Upvotes: 3

Franck Dernoncourt
Franck Dernoncourt

Reputation: 83427

The issue is that in t=0:1/fs:50; you start from 0, which explain why you get more than 100 samples.

One way to solve it:

 number_of_sample_data = 100;
 f=0.2;
 fs=2;
 A=100;%suppose that amplitude is 100
 q=20;
 t=0:1/fs:((number_of_sample_data-1)*1/fs);
 x=A*sin(2*pi*f*t+q);

which gives:

 >> length(x)

 ans =
 100

Upvotes: 2

Related Questions