In KDB, is there an equivalent of numpy's array.shape?

Viewed 161

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?

1 Answers

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);}
Related