Matlab create vectorized sequence

matlab, vectorization

Solution

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

Problem

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

Original source