KX Community

Find answers, ask questions, and connect with our KX Community around the world.
KX Community Guidelines

Home Forums kdb+ Updating input parameter over iteration

  • Updating input parameter over iteration

    Posted by mg4 on May 11, 2022 at 12:00 am

    Hi,

    I was wondering if there’s a way to run a function over x number of iterations and also update a second value based on the function’s output.

    For e.g.

    summer:{[ID;y;z] y:y+z; ID:ID+1}
    {summer[x;y;z]}[;2;2]/[{x<750};0]

    Currently this runs for 750 iterations however y and z are set to 2 on input so y always equals 4, I have checked this using namespaces.

    Is there a way to include another over somewhere so that y will run like 2+2=4, 4+2=6… for 750 iterations?

    Any help appreciated!!

    PS. The code is being used within peach, that’s why I can’t just use namespaces or a global variable to upsert into.

    mg4 replied 8 months, 1 week ago 3 Members · 5 Replies
  • 5 Replies
  • rocuinneagain

    Member
    May 11, 2022 at 12:00 am

    Something more like:

    q)750{(x[0]+1;x[1]+x[2];x[2])}/0

    0 2 750 1500 2

    Or use a dictionary for readability:

    q)750{x[`ID]+:1;x[`y]:sum x`y`z;x}/`ID`y`z!0 0 2

    ID| 750

    y | 1500

    z | 2

     

  • rocuinneagain

    Member
    May 11, 2022 at 12:00 am

    Is the / for of do what you are looking for?

    https://code.kx.com/q/ref/accumulators/#do

    q)750 +/2 2 
    754
  • mg4

    Member
    May 11, 2022 at 12:00 am

    Hey, thanks for the reply.

    So I think the above is quite close however it only allows you run sum, not appending to iteration id as required.

    Following similar to above:
    q)summer1:{[x;y] .m.x:x; x:x+y}

    q)750 summer1[;2]/2;
    q).m.x
    1500

     

    I’m probably missing something obvious but is there a way to manipulate this to append to ID per iteration so that:
    q)summer:{[ID;y;z] y:y+z;.m.id:.m.id,ID;.m.y:y; ID:ID+1}

    q).m.y

    1500 (as above)

    q).m.ID

    750 (missing piece)

     

    Thanks again!

  • mg4

    Member
    May 11, 2022 at 12:00 am

    The very one.

    Fair play and thanks!

  • Laura

    Administrator
    May 12, 2022 at 12:00 am

    See article on the accumulator iteration operators:

    https://code.kx.com/q/ref/accumulators/

Log in to reply.