Matlab Beginner Needs Help!

Discussion in 'Programmer's Corner' started by ruairdh, Nov 13, 2013.

  1. ruairdh

    Thread Starter New Member

    Nov 13, 2013
    1
    0
    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
     
  2. MrChips

    Moderator

    Oct 2, 2009
    12,442
    3,361
    Subscript n must begin with n = 1.

    You have another problem because y(n-1) for n = 1 has invalid subscript.
     
  3. blah2222

    Well-Known Member

    May 3, 2010
    554
    33
    This.

    You will need to start 'n' at 1 and have an initial condition for y[n-1] as MATLAB does not like indices of arrays that are less than 1.
     
  4. WBahn

    Moderator

    Mar 31, 2012
    17,747
    4,796
    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.
     
Loading...