Matlab Beginner Needs Help!

Thread Starter

ruairdh

Joined Nov 13, 2013
1
Hi, I'm new to this site and am trying to teach myself matlab. I came across this problem and can't seem to figure it out;

Write a MATLAB script to derive and plot y(n) below;

x(n) =[1 1 2 1 3] y(n)=x(n)+y(n-1)

I have written the following code;

N = 5;
x = [1 2 2 1 4];
n = 0:length(y)-1;
y(n)=x(n)+y(n-1);
stem(n,y)

...but MATLAB is giving me the following error message;

Subscript indices must either be real positive integers or logicals.

Error in test (line 4)

y(n)=x(n)+y(n-1);

Any help would be greatly appreciated.

Ruairdh
 

WBahn

Joined Mar 31, 2012
30,060
It's been a couple years since I've touched MatLab, so I'm not even going to try to get the syntax correct. So focus on the idea.

You have

N = 5;
x = [1 2 2 1 4];

This means that

x[1:5] is [1 2 2 1 4] (remember, I'm not trying to use MatLab syntax)

Now, what if we concatenate this with a matrix that has just a single element. Let's assume that I have a function called 'zeroes' that takes two arguments, the number of rows and columns, and returns a matrix that size filled with zeros. Let's further assume that we can contatentate two matrics by using a cat() function.

So

x_n_minus_1 = cat(zeroes(1,1), x) would yield [0 1 2 2 1 4];

while

x_n = cat(x, zeroes(1,1)) would yield [1 2 2 1 4 0];

Now I have

y = x_n + x_n_minus_1

which will have a length of N+1

I can put this all on one line

x_n = cat(x, zeroes(1,1)) + cat(zeroes(1,1), x);

I know you can do each of these things in MatLab and that, in doing so, you get somethign that generally runs much faster than using a loop. This is called "vectorizing" the problem and anytime you can vectorize a problem and eliminate a loop, the dividend is usually pretty impressive.
 
Top