# How can I mark points of the period length on stem of cos?

7 views (last 30 days)
nastia korzoun on 25 Jul 2021
Commented: nastia korzoun on 26 Jul 2021
Hi,
I have two subplots of two specific functions we are supposed to plot using stem (for discrete signal) (so far this went great).
Now we need to mark by red dots, the points of the period length starting from n=0.
I can't understand why it would only mark the origin point of n=0 with the red dot, and won't mark the other period length points.
The code I used:
n = linspace (0, 36 , 200);
%
X1 = cos((n.*pi)/4);
X2 = cos((3.*n.*pi)/8);
%
subplot(2, 1, 1);
stem (n, X1,"Marker","none",'Color','b');
hold;
ind1 = n==8.*((n.*pi)./4);
stem(n(ind1),X1(ind1),'Color','r','Marker',".","LineStyle","none")
xlim([0,36]);
ylim([-1.25,1.25]);
xlabel('Time(s)');
ylabel('Amplitude');
title('cos((npi)/4)');
grid;
%
subplot (2, 1, 2);
stem (n, X2,"Marker","none",'Color','b');
hold;
ind2 = n==(16./3).*((3.*n.*pi)./8);
stem(n(ind2),X2(ind2),'Color','r','Marker',".","LineStyle","none")
xlim([0,36]);
ylim([-1.25,1.25]);
xlabel('Time(s)');
ylabel('Amplitude');
title('cos((3npi)/8)');
grid;
The screenshot of the stem:
dpb on 25 Jul 2021
>> n = linspace (0, 36 , 200);
>> ind2 = n==(16./3).*((3.*n.*pi)./8);
>> whos ind2
Name Size Bytes Class Attributes
ind2 1x200 200 logical
>> sum(ind2)
ans =
1
>>

DGM on 26 Jul 2021
Edited: DGM on 26 Jul 2021
You're running into problems because your sampling rate means that your samples (other than the first one) don't neatly line up with the period of the underlying sinusoid. How you want to handle this is up to you. Consider the first plot alone. I'm using a different marker to make it easier to see.
n = linspace (0, 36 , 200);
X1 = cos((n.*pi)/4); % period is 8
stem (n, X1,"Marker","none",'Color','b');
hold on;
xlim([0,36]);
ylim([-1.25,1.25]);
xlabel('Time(s)');
ylabel('Amplitude');
title('cos((npi)/4)');
grid;
Since the samples don't exactly line up (zoom in at the crest near x=8), you might choose to mark the nearest sample:
% find minima by simple thresholding
%ind1 = rem(n,8) < 0.15;
%stem(n(ind1),X1(ind1),'Color','r','Marker',"*","LineStyle","none")
% a bit more robust minima finding method
[~,ind1] = findpeaks([0 8-rem(n,8)]);
stem(n(ind1-1),X1(ind1-1),'Color','r','Marker',"*","LineStyle","none")
Or you might choose to mark the exact period of the sinusoid:
% plot exact period instead of closest sample
xx = 0:8:36;
stem(xx,ones(size(xx)),'Color','r','Marker',"*","LineStyle",":")
If the latter case is appropriate, and your requirements allow it, a different method of visualization might be a bit easier to read:
% plot exact period using background
px = [0 8 8 0];
py = [-1.5 -1.5 1.5 1.5];
for pn = 1:ceil(36/16)
a = patch(px,py,'r','facealpha',0.1,'edgecolor','none');
uistack(a,'bottom')
px = px + 16;
end
nastia korzoun on 26 Jul 2021
This ie beyond perfect,
Thank you so much!!