1

I have a variable distr=[0 3 1 0 2];, and I have a variable full which should contrain distr(i) times i, for all i.

In this example, i want:

full=[2 2 2 3 5 5];

because distr(2)=3, therefore 3x 2, and so on.

Of course I can do it in a for-loop:

full=zeros([1,sum(distr)]);
cc=1;
for i=1:length(distr)
    curr=distr(i);
    full(cc:cc+curr-1)=i*ones([1,curr]);
    cc=cc+curr;
end

but that is very slow. Do you know of a fast way, using MATLAB's awesome array-oriented style? Thanks!

Mario Krenn
  • 223
  • 2
  • 13
  • 1
    You want __run-length decoding__. Use `repelem` as follows: `result = repelem(1:numel(distr), distr);`. Or see the linked question and answers for other approaches. – Luis Mendo Apr 18 '16 at 23:44
  • Ah, that is the correct name, i was not able to find results because i didn't know how to call this property. Thank you, that helps - in particular the performance tests there! – Mario Krenn Apr 19 '16 at 08:17

1 Answers1

2

Not sure, but maybe this will work. I can't check it since I currently don't have MATLAB:

full_tmp = arrayfun(@(i,n) i*ones(1,n),1:length(distr),distr,'uniformoutput',false);
full = cat(2,full_tmp{:});
aarbelle
  • 1,023
  • 8
  • 17