MATLAB: Please help with Index exceeds matrix dimensions error

MATLABsignal

%%here is my code
clc; close all;
N=50;
x = zeros(1,N);
for n = 1:length(x)
x(n)= sin((n/16)*pi);
end
y= zeros(1,N);
y(1)=-0.13;
for n = 2:length(x)
y(n+1)=(-1/3)*x(n+2)+(1/2)*x(n+1)+(1/3)*x(n)+y(n);
end
stem(0:1:50, y, 'r-');
xlabel('n');
ylabel('y[n]');
title('Output y[n] of the system');
pause;

Best Answer

This will eliminate the error:
for n = 2:length(x)-2
y(n+1)=(-1/3)*x(n+2)+(1/2)*x(n+1)+(1/3)*x(n)+y(n);
end
however you have to change the stem arguments accordingly:
stem(0:1:49, y, 'r-')