getting the following error Index exceeds matrix dimensions. Error in recur (line 32) y(i) = -a1*y(i-N:i-1)' + b1*x(i-N:i-N+M)';

my code:
% lab6 G00074212
%Input arguments
a = [1,-0.75,0.125];
b = [0,0.25];
%Since the system is starting from rest set
y0= zeros(1,3);%must match a length
x0= zeros(1,1);%must match b length
%Create the array 0-20
n = 0:20;
%define the signal
x = ones(1,1);%must be same length as y=1
y = recur(a,b,n,x,x0,y0);
%plot the graph
stem(n,y0);
title('Plot of unit step u[n]');
xlabel('n');
ylabel('u[n]');
recur code:
function y = recur(a,b,n,x,x0,y0);
%
% y = recur(a,b,n,x,x0,y0)
% solves for y[n] from:
% y[n] + a1*y[n-1] + a2*y[n-2]... + an*y[n-N]
% = b0*x[n] + b1*x[n-1] + ... + bm*x[n-M]
%
% a, b, n, x, x0 and y0 are vectors
% a = [a1 a2 ... aN]
% b = [b0 b1 ... bM]
% n contains the time values for which the solution will be computed
% y0 contains the initial conditions for y, in order,
% i.e., y0 = [y[n0-N], y[n0-N+1], ...,y[n0-1]]
% where n0 represents the first element of n
% x0 contains the initial conditions on x, in order
% i.e., x0 = [x[n0-M],...,x[n0-1]]
% the output, y, has length(n)
%
N = length(a);
M = length(b)-1;
if length(y0) ~= N,
error('Lengths of a and y0 must match')
end
if length(x0) ~= M,
error('Length of x0 must match length of b-1')
end
y = [y0 zeros(1,length(n))];
x = [x0 x];
a1 = a(length(a):-1:1); % reverses the elements in a
b1 = b(length(b):-1:1);
for i=N+1:N+length(n),
y(i) = -a1*y(i-N:i-1)' + b1*x(i-N:i-N+M)';
end
y = y(N+1:N+length(n));

Answers (1)

You are trying to access an array element that does not exist.
Consider:
>> X = [1,2,3] % only three elements
X =
1 2 3
>> X(4) % try to access the fourth element
Index exceeds matrix dimensions.
The error message even tells the line of code that causes the error:
y(i) = -a1*y(i-N:i-1)' + b1*x(i-N:i-N+M)';
On that line you have very complicated calculations involving M and N and i, in order to determine the subscript indices of two arrays y and x. One (or more) of these subscript indices is trying to access element/s of x of y that are outside the real size of x and/or y.

1 Comment

Hi Stephen, I believe then the matrix it is referencing is in the equation y(i) = -a1*y(i-N:i-1)' + b1*x(i-N:i-N+M)'; this equation is in the recur.m code from matlab. My guess is then that I have the wrong value in M? Tony

Sign in to comment.

Tags

Asked:

on 5 Nov 2015

Edited:

on 6 Nov 2015

Community Treasure Hunt

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

Start Hunting!