5

I have a MATLAB array and want to make a repetition based on the number of array elements. Below is the example that I want.

a = [2, 4, 6, 8]

If I want 7 elements, the result is

aa = [2, 4, 6, 8, 2, 4, 6]

Or if I want 5 elements,

aa = [2, 4, 6, 8, 2]

Is there any MATLAB function which makes these kind of result?

Edward M.
  • 221
  • 1
  • 5
  • 13
  • Take a look at the [repmat](https://ch.mathworks.com/help/matlab/ref/repmat.html) function. I'm not sure but it might help you. :) – Vuks Nov 28 '17 at 07:24
  • @V.L. Thanks for comment! I just checked repmat but it looks like only integer times of repetition is available. – Edward M. Nov 28 '17 at 07:27

2 Answers2

6

You can use "modular indexing":

a = [2, 4, 6, 8]; % data vector
n = 7; % desired number of elements
aa = a(mod(0:n-1, numel(a))+1);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
3

One simple option will be to use a temporary variable for that:

a = [2 4 6 8];
k = 7;
tmp = repmat(a,1,ceil(k/numel(a)));
aa = tmp(1:k)

First, you repeat the vector using the smallest integer that makes the result larger than k, and then you remove the excess elements.

If you do that many times you can write a small helper function to do that:

function out = semi_repmat(arr,k)
tmp = repmat(arr,1,ceil(k/numel(arr)));
out = tmp(1:k);
end
EBH
  • 10,350
  • 3
  • 34
  • 59
  • 1
    Yes. As your comment, I repeat the vector using the smallest integer (with floor function) and reduce the size. Thanks for comment! – Edward M. Nov 28 '17 at 08:05