How to vectorize this code?

 Classic List Threaded
3 messages
Reply | Threaded
Open this post in threaded view
|

How to vectorize this code?

 Hello Octavians!I have a long vector DIV (containing about 150,000 elements) which contains integers only from 32 to 64, inclusive.  I want to create a longer vector containing 1's repeated DIV(1) times, 2's repeated DIV(2) times, 3's repeated DIV(3) times, etc.  This is how I'm doing it now:  ind = [];  for j = 1:length(DIV)   ind = [ind ; j*ones(DIV(j),1)];  endI know there are some experts at vectorizing for-loop code like this.  Who can give this a shot?Thanks!-Brian
Reply | Threaded
Open this post in threaded view
|

RE: How to vectorize this code?

 It's been a while since I checked so I don't know if Octave has adopted the 'repelem' function from MATLAB.  If it has, then this task is accomplished by       ind = repelem(1:numel(DIV), reshape(DIV, 1, [])); Otherwise, you can use a standard CUMSUM incantation:     ind = zeros([sum(DIV), 1]);  # Preallocate     ind(cumsum([1 , reshape(DIV(1 : end – 1), 1, [])) = 1; # Put "1" at index jumps     ind = cumsum(ind);  # Realize those resulting indices Demo:  DIV = 1 : 5 => [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5] Regards, Bård Skaflestad SINTEF Digital, Mathematics & Cybernetics From: Help-octave [mailto:help-octave-bounces+bard.skaflestad=[hidden email]] On Behalf Of Brian Kaczynski Sent: onsdag 11. april 2018 13.24 To: [hidden email] Subject: How to vectorize this code?   Hello Octavians!   I have a long vector DIV (containing about 150,000 elements) which contains integers only from 32 to 64, inclusive.  I want to create a longer vector containing 1's repeated DIV(1) times, 2's repeated DIV(2) times, 3's repeated DIV(3) times, etc.  This is how I'm doing it now:     ind = [];   for j = 1:length(DIV)        ind = [ind ; j*ones(DIV(j),1)];   end   I know there are some experts at vectorizing for-loop code like this.  Who can give this a shot?   Thanks! -Brian
Reply | Threaded
Open this post in threaded view
|

Re: How to vectorize this code?

 On Wed, Apr 11, 2018, 8:56 AM Bård Skaflestad <[hidden email]> wrote: It's been a while since I checked so I don't know if Octave has adopted the 'repelem' function from MATLAB.  octave has a working, compatible implementation of repelem that should finally make the upcoming 4.4 release.You can download it in the meantime from