Reshape (#) doesn't work with a dynamic argument

172 Views Asked by At

To form a matrix consisting of identical rows, one could use

x:1 2 3
2 3#x,x

which produces (1 2 3i;1 2 3i) as expected. However, attempting to generalise this thus:

2 (count x)#x,x

produces a type error although the types are equal:

(type 3) ~ type count x

returns 1b. Why doesn't this work?

2

There are 2 best solutions below

0
On BEST ANSWER

The following should work.

q)(2;count x)#x,x
1 2 3
1 2 3

If you look at the parse tree of both your statements you can see that the second is evaluated differently. In the second only the result of count is passed as an argument to #.

q)parse"2 3#x,x"
#
2 3
(,;`x;`x)
q)parse"2 (count x)#x,x"
2
(#;(#:;`x);(,;`x;`x))
0
On

If you're looking to build matrices with identical rows you might be better off using rownum#enlist x

q)x:100000?100
q)\ts do[100;v1:5 100000#x,x]
157 5767696j
q)\ts do[100;v2:5#enlist x]
0 992j
q)v1~v2
1b

I for one find this more natural (and its faster!)