Search code examples
arraysmatlabloopssignals

Create two vectors in matlab using for loop


I am trying to create two vectors first:

[ 10     9     8     7     6     5     4     3     2     1     2     3     4     5     6     7     8     9    10 ]

second:

[ 1     2    3     4     5    6     7     8     9     10     9     8     7     6    5     4    3     2    1 ]

I had almost no problems with the first one:

i = 1:10;
for t = 1: 2*length(i)-1
     y1(t) = abs(length(x)-t)+1; 
end

But there are some problems with the second... Does anyone have any idea how I can create it using the same for loop?Thanks in advance


Solution

  • If you want to do it with a loop:

    N = 10;
    for t = 1:2*N-1
        y2(t) = -abs(t-N)+N; 
    end
    

    But its probably easier to use the following, first make an array 1:N, and then concatenate the array N-1:-1:1:

    y2 = [1:N, N-1:-1:1]