Using a For Loop to plot a sample range for a difference equation

조회 수: 13 (최근 30일)
Liam Brennan
Liam Brennan 2022년 4월 20일
답변: Voss 2022년 4월 21일
Basically I cant figure out how to intitally set up my code to run x(n) and y(n) for 101 to 500 samples. any help is much appreciated.

답변 (1개)

Voss
Voss 2022년 4월 21일
Given in the question:
% input signal
% x(n) = cos(pi/60*n), n = 0,1,2,...,999
%
% output signal
% from difference equation
% y(n) = 0.5*y(n-1) + x(n)
% and initial condition
% y(-1) = 0
Since the output signal y(n) has to start at n = -1, the vector y (to be constructed in MATLAB) has to have 1001 elements (for n = -1 to n = 999). It is convenient for the vector x to have the same size as y, so that the ith element of x corresponds to the ith element of y (but this is not strictly necessary).
The point is that indexing starts at 1 in MATLAB, so index 1 in vectors x and y will correspond to n = -1 in signals x(n) and y(n). (So the vector x will have 1001 elements with the 1st element corresponding to n = -1, but the first element of x won't be used.)
N = 1000;
% n = -1 to n = 999:
n = -1:N-1;
% x(n) at n=-1 is NaN, after that x(n)=cos(pi/60*n):
x = [NaN cos(pi/60*n(2:end))];
% initialize vector y to have 1001 elements:
y = NaN(1,N+1);
% y(n)=0 at n=-1:
y(1) = 0; % n=-1 corresponds to index 1 in vector y
% y(n) = 0.5*y(n-1) + x(n):
for ii = 2:N+1 % n = 0,...,999 <-> ii = 2:1001
y(ii) = 0.5*y(ii-1) + x(ii);
end
% a table to summarize the situation
t = table(n.',(1:N+1).',x.',y.', ...
'VariableNames',{'signal index n','vector index ii','x=cos(pi/60*n)','y'});
head(t)
ans = 8×4 table
signal index n vector index ii x=cos(pi/60*n) y ______________ _______________ ______________ ______ -1 1 NaN 0 0 2 1 1 1 3 0.99863 1.4986 2 4 0.99452 1.7438 3 5 0.98769 1.8596 4 6 0.97815 1.908 5 7 0.96593 1.9199 6 8 0.95106 1.911

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by