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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With