I'm trying to work with matrices in KDB, and am frequently having to query their dimensions.
Currently I'm doing count and count flip, but this is verbose and repetitive. Is there a more elegant way to query the dimensions of an n-D matrix?
Assuming that we are in front of a well formed matrix, a function that would achieve your objective is:
shape:{:(count x;count x[0]);};
If you use it very often, you can save in the startup file q.q in the q directory, so it is going to be loaded on launch and readily available.
Clearly, flipping the entire matrix is more expensive in terms of time:
t:(100;100)#til 10000
q)\t:1000000 {:(count x; count flip x);}[t]
33808
q)\t:1000000 {:(count x;count x[0]);}[t]
282
Having said that, the flip method will guarantee that the matrix is well formed, which is not going to be caught by the proposed method:
q)t2:((2;3;4);(2;3))
q){:((#)x;(#)x[0]);}[t2]
2 3
q){:(count x; count flip x);}[t2]
'length
[1] {:(count x; count flip x);}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With