Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repetition of array elements in MATLAB

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?

like image 738
Edward M. Avatar asked Nov 28 '17 07:11

Edward M.


2 Answers

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);
like image 175
Luis Mendo Avatar answered Sep 20 '22 16:09

Luis Mendo


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
like image 41
EBH Avatar answered Sep 20 '22 16:09

EBH