cjm2671
cjm2671

Reputation: 19486

How do I evaluate a function into a matrix in KDB?

Let's say I've got a function that defines a matrix in terms of it's i and j coordinates:

f: {y+2*x}

I'm trying to create a square matrix that evaluates this function at all locations.

I know it needs to be something like f ' (til 5) /:\: til 5, but I'm struggling with rest.

Upvotes: 0

Views: 139

Answers (2)

SJT
SJT

Reputation: 1097

You were close. But there is no need to generate all the coordinate pairs and then iterate over them. Each Right Each Left /:\: manages all that for you and returns the matrix you want.

q)(til 5)f/:\:til 5
0 1 2  3  4
2 3 4  5  6
4 5 6  7  8
6 7 8  9  10
8 9 10 11 12

Upvotes: 0

Igor Korkhov
Igor Korkhov

Reputation: 8558

Rephrasing your question a bit, you want to create a matrix A = [aij] where aij = f(i, j), i, j = 0..N-1.

In other words you want to evaluate f for all possible combinations of i and j. So:

q)N:5;
q)i:til[N] cross til N; / all combinations of i and j
q)a:f .' i;             / evaluate f for all pairs (i;j)
q)A:(N;N)#a;            / create a matrix using #: https://code.kx.com/q/ref/take/
0 1 2  3  4
2 3 4  5  6
4 5 6  7  8
6 7 8  9  10
8 9 10 11 12

P.S. No, (til 5) /:\: til 5 is not exactly what you'd need but close. You are generating a list of all pairs i.e. you are pairing or joining the first element of til 5 with every element of (another) til 5 one by one, then the second , etc. So you need the join operator (https://code.kx.com/q/ref/join/):

(til 5),/:\: til 5

Upvotes: 4

Related Questions