Q Idioms assemembered

This is more of an expanding list of Q idioms I have had to either assemble or remember or some combination.

  1. Cross product of two lists is faster in table form

    q)show x:til 3
    0 1 2
    q)show y:2#7
    7 7
    q)x cross y
    0 7
    0 7
    1 7
    1 7
    2 7
    2 7
    q) ([] x) cross ([] y)
    x y

    0 7
    0 7
    1 7
    1 7
    2 7
    2 7
    \t til[1000] cross 1000#5
    85
    \t flip value flip ([] til 1000) cross ([] x1:1000#5)
    33
    /and if you are happy working with it in table form
    \t ([] til 1000) cross ([] x1:1000#5)
    5

  2. Take last N observations for a column in a table
    Both of these can be used to create a list of indexes and the columns can be simply   projected on to the list of indexes

    /a) Intuitive way take last n from c
    q) N:10; C:til 100000;
    q) {[n;c]c{y-x}[til n] each til count c}[N;C] /timing 31 milli
    0
    1 0
    2 1 0
    3 2 1 0
    4 3 2 1 0
    ….
    /b) Faster way using xprev and flip
    q) \t {[n;c] flip (1+til n) xprev \\: c}[10;c]  /timing 9 millesec

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s