Search code examples
matlabmatrixdiagonal

Selecting Principal Diagonal Elements


In the matrix shown below how can I select elements 01, 09, 17 and 25. From Egon's answer to my earlier question Select Diagonal Elements of a Matrix in MATLAB I am able to select the central value 25 using c = (size(A)+1)/2; but I am wondering how to select above mentioned elements in NW direction.

A = [01 02 03 04 05 06 07
     08 09 10 11 12 13 14
     15 16 17 18 19 20 21
     22 23 24 25 26 27 28
     29 30 31 32 33 34 35
     36 37 38 39 40 41 42
     43 44 45 46 47 48 49];

Solution

  • Use diag to get elements on the diagonal.

    diagA = diag(A)
    

    You can restrict this to the elements from the top left to the middle with

    n = ceil(size(A, 1) / 2)
    diagA(1:n)