Search code examples
kdb

How to do sum of list subset in kdb?


If you have a list and another list with indices (limited number) in of the first list in ascending order.

How can you get a sum of elements in the first list between consecutive indices in the second list.

e.g:

list1: til 100;
idx: (1 20 50 70 100);

How can we get a list with sum of elements of list from elements 1:20, 20:50, 50:70, 70:100?

The obvious approach would be to use # and _ on elements of the idx but can we do that iteratively somehow without using first, first 1_idx etc.


Solution

  • Something like this would work:

    q)sum each idx cut list1
    190 1035 1190 2535 0
    

    cut operates by cutting the second argument at the indices given in the first. Hence why you see the 0 at the end of the result, as it's cutting at the 100th element.