jim
jim

Reputation: 53

Matlab create vectorized sequence

I want to construct a function that accepts input n and gives the vector

[n n-1 n-2 ... n-n, n-1 n-2 ... n-n, ..., n-n]

//Example 
input :  n=3 
output : [3 2 1 0 2 1 0 1 0 0]

I know how to do this using loops, but I'm looking for a clever way to do it in MATLAB

Upvotes: 5

Views: 103

Answers (2)

mmumboss
mmumboss

Reputation: 699

You can use repmat to repeat the matrix a few times, and then select only the triangular part by means of tril. Like this:

n=3;
x=repmat(n:-1:0,1,n+1);
result=x(tril(ones(n+1))>0)

Or in one line:

n=3;
getfield(repmat(n:-1:0,1,n+1),{reshape(tril(ones(n+1))>0,1,(n+1)^2)})

The result of this function is the desired output:

result =

     3     2     1     0     2     1     0     1     0     0

Upvotes: 7

Stewie Griffin
Stewie Griffin

Reputation: 14939

Since you haven't gotten any answers, here's a way to do it:

N = 3;
x = repmat(N:-1:0,1,N+1)-cumsum(repmat([1 zeros(1,N)],1,N+1))+1
x = x(x>=0)
x =
    3   2   1   0   2   1   0   1   0   0

Upvotes: 4

Related Questions