Matrix q中的一般位置查找函数
我需要类似Mathematica()的位置函数,但在Q中,我对矩形矩阵的解如下:Matrix q中的一般位置查找函数,matrix,position,find,kdb,q-lang,Matrix,Position,Find,Kdb,Q Lang,我需要类似Mathematica()的位置函数,但在Q中,我对矩形矩阵的解如下: q) colrow:{sz:count x; $[(count first x) = 1; enlist y; (floor y % sz; y mod sz)]} q) position:{flip colrow[x;(where raze x = y)]} 它直接适用于矩形矩阵和列表: q) t:(1 -1 1; / matrix test -1 3 4; 1 -1 1);
q) colrow:{sz:count x; $[(count first x) = 1; enlist y; (floor y % sz; y mod sz)]}
q) position:{flip colrow[x;(where raze x = y)]}
它直接适用于矩形矩阵和列表:
q) t:(1 -1 1; / matrix test
-1 3 4;
1 -1 1);
q) pos1:position[t;-1] / try to find all positions of -1
q) pos1
0 1
1 0
2 1
q) t ./: pos1 / here get items
-1 -1 -1
q) l:1 0 3 0 2 3 4 1 0 / list test
q) pos2:position[l;0] / try to find all positions of 0
q) pos2
1
3
8
q) l ./: pos2 / get items
0 0 0
这是可行的,但对于任意列表,而不仅仅是矩形矩阵,最好有更通用的解决方案。例如,对于以下参数,上面的代码无法正常工作:
position[(1 2 3; 1 2; 1 2 1 4); 1]
可能有人有通用的解决方案吗?这看起来怎么样?我认为它应该适用于所有二维列表,不规则或矩形,也适用于向量。(我还没有为任意尺寸制定出一个版本。) 编辑: 这是一个适用于除1(当然还有0)之外的所有维度的版本: 但是,在向量上,它返回的是地址向量,而不是地址矩阵,因此它必须与
@
一起使用,而不是
:
q)0N!position2[l;0];
1 3 8
q)l ./:position2[l;0]
'type
q)l position2[l;0]
0 0 0
q)
如果你真的需要它以同样的方式处理向量,就像处理高维结构一样,最简单的解决方案可能就是直接对它们进行特殊处理:
q)position3:{$[type x;enlist each where@;{$[type x;where x;raze each raze flip each flip(til count x;.z.s each x)]}]x=y}
q)position3[l;0]
1
3
8
q)l ./:position3[l;0]
0 0 0
q)r2 ./:position3[r2;1]
1 1 1 1 1 1 1 1
q)r ./:position3[r;1]
1 1 1 1
q)t ./:position3[t;-1]
-1 -1 -1
q)
下面的内容也可以使用。
不是精确的解决方案,但可行
pos:{$[type x;where x=y;where each x=y]}
val:{raze ($[0h=type x;x@';x@])pos[x;y]}
q)t:(1 -1 1;-1 3 4;1 -1 1)
q)pos[t;-1]
1
0
1
q)val[t;-1]
-1
-1
-1
q)l:1 0 3 0 2 3 4 1 0
q)pos[l;0]
1 3 8
q)val[l;0]
0 0 0
q)r:(1 2 3; 1 2; 1 2 1 4)
q)pos[r;1]
,0
,0
0 2
q)val[r;1]
1 1 1 1
优秀的解决方案,亚伦!
q)position3:{$[type x;enlist each where@;{$[type x;where x;raze each raze flip each flip(til count x;.z.s each x)]}]x=y}
q)position3[l;0]
1
3
8
q)l ./:position3[l;0]
0 0 0
q)r2 ./:position3[r2;1]
1 1 1 1 1 1 1 1
q)r ./:position3[r;1]
1 1 1 1
q)t ./:position3[t;-1]
-1 -1 -1
q)
pos:{$[type x;where x=y;where each x=y]}
val:{raze ($[0h=type x;x@';x@])pos[x;y]}
q)t:(1 -1 1;-1 3 4;1 -1 1)
q)pos[t;-1]
1
0
1
q)val[t;-1]
-1
-1
-1
q)l:1 0 3 0 2 3 4 1 0
q)pos[l;0]
1 3 8
q)val[l;0]
0 0 0
q)r:(1 2 3; 1 2; 1 2 1 4)
q)pos[r;1]
,0
,0
0 2
q)val[r;1]
1 1 1 1