How can I mark points of the period length on stem of cos?
조회 수: 8 (최근 30일)
이전 댓글 표시
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:
댓글 수: 1
dpb
2021년 7월 25일
>> 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
2021년 7월 26일
편집: DGM
2021년 7월 26일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Stem Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!