Repeating array elements in MATLAB

I have a MATLAB array and you want to do a repeat based on the number of elements in the array. Below is the example I want.

a = [2, 4, 6, 8] 

If I need 7 elements, the result

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

Or, if I need 5 elements,

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

Is there any MATLAB function that does such a result?

+5
source share
2 answers

One simple option is to use a temporary variable for this:

 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, which makes the result larger than k , and then you remove the extra elements.

If you do this many times, you can write a small helper function for this:

 function out = semi_repmat(arr,k) tmp = repmat(arr,1,ceil(k/numel(arr))); out = tmp(1:k); end 
+3
source

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); 
+6
source

Source: https://habr.com/ru/post/1273706/


All Articles