Gary
Gary

Reputation: 2007

(KDB+/q) Get diagonal elements of a matrix

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

Answers (1)

Anton Dovzhenko
Anton Dovzhenko

Reputation: 2569

Following code returns diagonal elements of matrix

(1 2 3; 4 5 6; 7 8 9) @' til 3

The code

  1. generates continuous list 0, 1, 2 on the right
  2. Gets an element from every list on the left by applying corresponding index 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

Related Questions