2

I have an array freq with frequencies and another one val with values.

val =[1 3 5 7];    
freq=[2 3 3 2];

I want to get the array result.

result=[1 1 3 3 3 5 5 5 7 7];

One of the methods I've tried to get result is:

freq=[2 3 3 2];
val=[1 3 5 7];
result=[];
for i=1:length(val);
    result=[result repmat(val(i),1,freq(i))];
end

It works, but with large arrays I expect some performance gain if I get rid of the for-loop. Is there any built in function for this? How would you calculate result for large arrays?

Gypaets
  • 125
  • 5
  • Minor improvement to the loop can be achieved by preallocating `result` to `result = zeros(1, sum(freq))`, and handling indexing appropriately in the loop. – mikkola Dec 04 '15 at 12:26

2 Answers2

5

This can be made that way:

val = [1 3 5 7]
freq = [2 3 3 2]
res = repelem(val, freq)

res =

 1     1     3     3     3     5     5     5     7     7
Mikhail_Sam
  • 10,602
  • 11
  • 66
  • 102
2

For large vectors, you could gain some performance by preallocating result and updating multiple cells at the same time.

result = zeros(sum(freq), 1);
j = 1;
for i=1:length(freq);
    result(j:j+freq(i)-1) = val(i);
    j = j + freq(i);
end;
dusk
  • 1,799
  • 18
  • 25