How can I 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?

%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

 Accepted 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

2 Comments

Thank you! I realized what I was doing was simply repeating all elements an amount of times equal to the last NN element.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!