1

I want to create an array of length Ns(Ns+1) and I need the first Ns elements to be 0, the next Ns elements to be 1, ..., the last Ns to be Ns.

I am well aware that there are plenty of ways to do this with for-loops, which I want to avoid for this particular task. I am looking for a way to do this using matlab functions and notions of vectorization.

For example, I had a similar array that I wanted to populate with 0, 1, 2, ..., Ns, 0, 1, 2, ..., Ns, 0, 1, 2, ... and I accomplished that with

my_array = repmat(0:Ns, 1, Ns+1);

Is there a similar approach to be taken to achieve my purpose?

One thing I thought I could do would be to create a matrix like

0 0 0 ... 0
1 1 1 ... 1
... ... ...
Ns Ns .. Ns

and then concatenating the lines; I would know how to create the matrix but not how to concatenate the lines into an array.

Are there any other ways? Suggestions of commands are also acceptable!

Thanks.

RGS
  • 964
  • 2
  • 10
  • 27

3 Answers3

6

You could do it with repmat, but it's straightforward with repelem:

my_array = repelem(0:Ns, Ns);
beaker
  • 16,331
  • 3
  • 32
  • 49
4

Here's another way:

result = ceil(-1+1/Ns:1/Ns:Ns);

Or, for a general array:

data = [4 1 2 5];
Ns = 3;
result = data(ceil(1/Ns:1/Ns:numel(data)));

which gives

result =
     4     4     4     1     1     1     2     2     2     5     5     5

This can be done even without ceil, exploiting implicit rounding in colon indices (not documented; more fun than practical):

data = [4 1 2 5];
Ns = 3;
result = data(.5:1/Ns:numel(data)+.5-1/Ns);
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
3

The reshape command may be relevant

>> Ns = 3;
>> a = repmat(0:Ns, Ns, 1)
a =
 0     1     2     3
 0     1     2     3
 0     1     2     3

>> b = reshape(a, 1, [])
b =
 0     0     0     1     1     1     2     2     2     3     3     3
dkv
  • 6,602
  • 10
  • 34
  • 54