MATLAB Answers

## Is there a smarter way to create a large vector, with repeated numbers in a diminishing quantity?

Asked by Adam Quintero

### Adam Quintero (view profile)

on 3 Jun 2011
Accepted Answer by Sean de Wolski

### Sean de Wolski (view profile)

I need the vector to begin with 144 evenly spaced '2's, then 143 '3's, then 142 '4's, etc. I see the brute force method, but it doesn't seem very smart. Is there a way to get Matlab to create this vector for me?
thx

Igor

### Igor (view profile)

on 3 Jun 2011
Valid code --
n=14;A1=(1:n)'*ones(1,n);A2=triu(A1)';A3=reshape(A2,1,n^2);A=A3(A3~=0),
Sean de Wolski

### Sean de Wolski (view profile)

on 3 Jun 2011
Any question that makes a golf challenge gets a vote from me!

Sign in to comment.

## 5 Answers

Answer by Sean de Wolski

### Sean de Wolski (view profile)

on 3 Jun 2011
Accepted Answer

A one liner:
n = 144;
v = sort(nonzeros(triu(bsxfun(@times,(2:n+1).',ones(1,n)))));
or
v = sort(nonzeros(triu(toeplitz(2:n+1))));
Golf!
v=hankel(n+1:-1:2);
v=sort(v(~~v))
%33 characters
transpose it if you want a row vector.

#### 0 Comments

Sign in to comment.

Answer by Friedrich

### Friedrich (view profile)

on 3 Jun 2011

I think the repmat command can help:
[repmat(2,144,1);repmat(3,143,1);repmat(4,142,1)]

Igor

### Igor (view profile)

on 3 Jun 2011
no :) 144 times?
n=144;
A1=(1:n)'*ones(1,n);
A2=tril(A1);
A3=reshape(A2...);
find... all zero elements
Friedrich

### Friedrich (view profile)

on 3 Jun 2011
Upps^^, than this way:
start_repeat = 144;
start_number = 2;
final_size = (start_repeat+1)*start_repeat / 2;
final_vec = zeros(final_size,1);
index = 1;
for i=start_repeat:-1:1
final_vec(index:index+i-1,1) = repmat(start_number+start_repeat-i,i,1);
index = index + i;
end

Sign in to comment.

Answer by Igor

### Igor (view profile)

on 3 Jun 2011

[1,2,2,3,3,3,4,4,4,4,...] similar task
n=1:10 trinv(n) = floor((1+sqrt(1+8*n))/2)
(<http://oeis.org/A002024>)

#### 0 Comments

Sign in to comment.

Answer by Oleg Komarov

### Oleg Komarov (view profile)

on 3 Jun 2011

Using rude for run length decoding:
n = 144;
val = 1:n;
len = val;
Out = rude(len,val); % rude on fex

#### 0 Comments

Sign in to comment.

Answer by Andrei Bobrov

### Andrei Bobrov (view profile)

on 3 Jun 2011

n = 144;
vm = triu(repmat(n+1:-1:1,n+1,1));
vm(vm>0);

Igor

on 3 Jun 2011
:) shortest :)
Sean de Wolski

### Sean de Wolski (view profile)

on 3 Jun 2011
Isn't right...

Sign in to comment.