Reputation: 2007
I want to get all the diagonal elements of a matrix in kdb+/q.
E.g.
q)A:(1 2 3; 4 5 6; 7 8 9)
q)A
1 2 3
4 5 6
7 8 9
would return 1 5 9
My idea is to use "." to get the elements.
q) A . 1 1 / one of the diagonal elements
5
q) 2 #' til 3 / indices
0 0
1 1
2 2
But I tried many ways and can't get it working.
Upvotes: 1
Views: 467
Reputation: 2569
Following code returns diagonal elements of matrix
(1 2 3; 4 5 6; 7 8 9) @' til 3
The code
0, 1, 2
on the right@'
adverb)Generic form looks like:
getDiagonal: {x@'til count x};
getDiagonal (1 2 3; 4 5 6; 7 8 9)
Upvotes: 3