Search code examples
vectorapldyaloginterleave

How to interleave two given vectors in APL


I'm trying to solve a problem using APL, for which I have two vectors v1 and v2, with relative length of at most +1, depending on the input. That means that ((≢v1)-(≢v2))∊¯1 0 1.

What would be the best way to interleave said vectors, so to create a third vector v3 such that v3=v1[0],v2[0],v1[1],v2[1],...?

(If it's relevant, I'm using Dyalog APL version 16.0)


Solution

  • This should work in just about every APL.

    (v0,v1)[⍋(⍳⍴v0),⍳⍴v1]
    

    If you want to worry about either v0 or v1 being scalars, then

    (v0,v1)[⍋(⍳⍴,v0),⍳⍴,v1]