user3020151
user3020151

Reputation: 51

Generate a vector in MATLAB

I am trying to solve a MATLAB problem to generate a vector like 1,2,2,3,3,3,4,4,4,4...

So if n = 3, then return

[1 2 2 3 3 3] And if n = 5, then return

[1 2 2 3 3 3 4 4 4 4 5 5 5 5 5]

This is what I came up with:

ans=1
for n=2:n
ans=[ans n*ones(1,n)]
end

But I'm trying to minimize the code length. Anyone have any ideas?

Upvotes: 2

Views: 1644

Answers (8)

Sam Hallenbeck
Sam Hallenbeck

Reputation: 1

Here's a short one

function ans = your_fcn_name(x)
   ans = repelem(1:x, 1:x)
end

Upvotes: 0

Aimane_Ned
Aimane_Ned

Reputation: 1

it is a litle bit longer

function y = your_fcn_name(n)
      N = sum(1:n);w = [] ; 
      for i=1:n
         q(1:i) = i;
         w      = [w q(1:i)];
      end
      y = w;
end

Upvotes: 0

mc2
mc2

Reputation: 393

A little 'magic' solution:

ceil(sqrt(2*(1:(n^2+n)/2))-0.5)

See visualisation: enter image description here This is the plot of function sqrt(2*(1:(n^2+n)/2))-0.5:

plot(1:(n^2+n)/2,sqrt(2*(1:(n^2+n)/2))-0.5,'.')

where xticklabels were changed according the following code:

set(gca,'xtick',cumsum(0:n),'xticklabel',0:n)

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112659

Here's another one-liner. Unlike solutions based on triu, this one doesn't generate extra elements as intermediate results (that doesn't mean it's faster, though):

fliplr(cumsum([n full(sparse(ones(1,n-1),cumsum(n:-1:2),-1))]))

Upvotes: 0

bla
bla

Reputation: 26069

In the same spirit, here's my one liner:

nonzeros(triu(meshgrid(1:n)))'

Upvotes: 2

chappjc
chappjc

Reputation: 30579

This is similar to jkshah's answer, but I would approach it slightly differently,

n=5;
M = ones(n,1)*(1:n)
B = M(triu(ones(n))>0)';

Upvotes: 0

jkshah
jkshah

Reputation: 11703

n = 5;
A = triu(ones(n,1)*(1:n));
A(A==0) = [];

Upvotes: 1

Robert Seifert
Robert Seifert

Reputation: 25232

still a few lines:

n = 5;     %number of elements

A(cumsum(0:n)+1) = 1;
B = cumsum(A(1:end-1))

returns

1   2   2   3   3   3   4   4   4   4   5   5   5   5   5 

Upvotes: 2

Related Questions