Point out the error from this code

kindly Point out the error from this code as I am getting this message "Subscript indices must either be real positive integers or logicals"
% Initialize Variables
startTime = -20-9;
endTime = 40-9;
n = startTime:endTime;
x = zeros(size(n));
% Define x
x(abs(n) == 5 ) = 1.5;
x(abs(n) == 4 ) = 3;
x(abs(n) == 3 ) = 1;
x(abs(n) == 2 ) = 0;
x(abs(n) == 1) = -0.5;
x(n == 0) = 2;
y = zeros(size(n));
for i = 1:length(n)
if i > 1 % for i=1 cannot look back in time , i.e. there is no x(0)
y(i) = 5*x(i) + 5/3.* x(i-2) -2*x(i-5)+1/2.*x(i+2)+1/2.*y(i-2)-1/4.*y(i-4);
else
y(i) = 5*x(i);
end
end % Compute y[n] here. Be sure to account for edge conditions. (See
% MATLAB Tutorial 2 Lecture code for an example)
disp([num2str(toc*1000) ' ms' ]); % display run time in ms on cmd line
figure;
subplot(2,1,1);
stem(n,x, 'k' );
ylim([0 1.5]);
xlabel('n' , 'fontsize' ,13)
ylabel('amplitude' , 'fontsize' ,12)
title('x[n]' , 'fontsize' ,13)
subplot(2,1,2);
stem(n,y, 'r' );
ylim([0 1.5]);
xlabel('n' , 'fontsize' ,13)
ylabel('amplitude' , 'fontsize' ,12)
title('y[n]' , 'fontsize' ,13)

1 commentaire

Guillaume
Guillaume le 12 Oct 2015
debug by forum is probably the least efficient way of debugging your code. You're better off using the tools provided by matlab.
In any case, the error message will also include a line number and the actual code that triggered the error. Please post this, rather than letting us guess.

Réponses (2)

Thorsten
Thorsten le 12 Oct 2015
Modifié(e) : Thorsten le 12 Oct 2015

0 votes

Your i runs from 1 to length(n), and you try to address x(i-5), x(i-2), i.e, x(-4), x(-1) for i=1. That's wrong, indices have to be positive in Matlab.
the cyclist
the cyclist le 12 Oct 2015
Modifié(e) : the cyclist le 12 Oct 2015
In this line
y(i) = 5*x(i) + 5/3.* x(i-2) -2*x(i-5)+1/2.*x(i+2)+1/2.*y(i-2)-1/4.*y(i-4);
you look back up to 5 time periods, so you are trying to access
y(-3)
when i = 2. That element obviously does not exist.

Cette question est clôturée.

Tags

Clôturé :

le 20 Août 2021

Community Treasure Hunt

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

Start Hunting!

Translated by