plot discrete time function x(n)=y(n-2). it shows error (Attempted to access y(-1); index must be a positive integer or logical.)

clc;
clear all;
x=-5:1:5;
for n=1:11
if x(n)>=-3&&x(n)<=3
y(n-2)=2*x(n);
else
y(n-2)=0;
end
end
stem(x,y)
xlabel('n')% x-axis label
ylabel('x(n)')% y-axis label

 Accepted Answer

This error is expected. You are trying to access an index (n-2) even when n is 1 or 2... which MATLAB does not know how to interpret, as vector indices start at 1.
You could add some sort of protection around the edge cases n=1 and n=2 which would cause issues:
if n > 2
y(n-2) = 2*x(n);
end
This would make y be 2 elements shorter than x, which may or may not be what you want.
- Sebastian

More Answers (0)

Categories

Find more on Graphics Performance in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!