MATLAB: How to create a new array from an original array, where the new array’s elements appear for a number of times equal to the original’s elements’ value

arrayconcatenationduplicateMATLABmatricesmatrixnumberrepelemvector

%Suppose I have an array NN=[108,92,91,127]. I want a new array "E" to contain 108+92+91+127 elements in total, where the first 108 elements are also numerically equal to 108,the next 92 elements are equal to 92 and so on and so forth. The given code seems problematic, as the number of times the elements appear in E differ from the original value.
E=[];
NN=[108;92;91;127];
for i=1:length(NN)
E=repelem(NN,NN(i));
end

Best Answer

The repelem function will do what you want and without the loop.
Using a simpler version of ‘NN’ to illustrate:
NN = [2 3 4];
V = repelem(NN,NN)
V =
2 2 3 3 3 4 4 4 4
Related Question