Search code examples
kdb

KDB+/Q: Efficient way of padding an irregular list of lists (matrix)


given the following list of lists:

q)m
  1 1
  1 1 
  1 1 1

What is an effective method of producing a regular matrix (padding empty spaces with 0) as shown below:

q)m
  1 1 0
  1 1 0
  1 1 1

Thanks


Solution

  • One method is the below:

    q)m:(1 1;1 1;1 1 1)
    q){x,'(max[c]-c:count each x)#'0}m
    1 1 0
    1 1 0
    1 1 1
    

    Just find the difference in length between the longest row and the other rows and append that number of zeroes.