Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 929
jim Avatar asked Feb 06 '14 12:02

jim


2 Answers

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
like image 128
mmumboss Avatar answered Sep 19 '22 20:09

mmumboss


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
like image 36
Stewie Griffin Avatar answered Sep 23 '22 20:09

Stewie Griffin