Using a For Loop to plot a sample range for a difference equation
조회 수: 13 (최근 30일)
이전 댓글 표시
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.

댓글 수: 0
답변 (1개)
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)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!