Search code examples
arraysloopsvectorlist-comprehensionopenscad

How to create vector elements in pairs in a FOR loop in OpenSCAD


My aim is to create 2D vector elements in pairs, using a FOR loop. Consider the following example (not my real example - just something simplified to describe the problem):

    step1 = [ for (i=[1:5]) 
        [i,2*i+3]
    ];
    
    step2 = [ for (i=[1:5]) 
        [-i,2*i+2]
    ];
    
    steps = [ for (i=[1:5]) 
        concat([step1[i-1]],[step2[i-1]])
    ];
 
echo(step1);
echo(step2);
echo(steps);

The step1 vector looks like this: [[1, 5], [2, 7], [3, 9], [4, 11], [5, 13]]

The step2 vector looks like this: [[-1, 4], [-2, 6], [-3, 8], [-4, 10], [-5, 12]]

My target is to interleave the elements of step1 and step2 to produce:
[[1, 5], [-1, 4], [2, 7], [-2, 6], [3, 9], [-3, 8], [4, 11], [-4, 10], [5, 13], [-5, 12]]

The closest I've been able to achieve so far uses 'concat' as above, but this treats each concatenated pair as a separate vector, and therefore puts an additional square bracket round each interleaved pair, as follows:
[[[1, 5], [-1, 4]], [[2, 7], [-2, 6]], [[3, 9], [-3, 8]], [[4, 11], [-4, 10]], [[5, 13], [-5, 12]]]

If I try to create each pair of elements in a single loop, e.g.

    steps = [ for (i=[1:5]) 
        [i,2*i+3],[-i,2*i+2]
    ];

then I get an 'unknown variable' error for the loop variable for the element after the comma.

There must be an easy way to do this - can anyone help?


Solution

  • I think that is exactly what keyword each is for.

    steps = [ for (i=[1:5]) 
            each [step1[i-1],step2[i-1]]
    ];