Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create vector from elements other than diagonal ones

I would like to create a column vector from the elements of a matrix A of size (3,3) that are not on the diagonal. Thus, I would have 6 elements in that output vector. How can I do this?

like image 918
Ghazwan Alsoufi Avatar asked Jan 29 '26 21:01

Ghazwan Alsoufi


2 Answers

Use eye and logical negation, although this is no better than Divakar's original answer, and possibly significantly slower for very large matrices.

>> A = magic(4)
A =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1
>> A(~eye(size(A)))
ans =
     5
     9
     4
     2
     7
    14
     3
    10
    15
    13
     8
    12
like image 200
chappjc Avatar answered Feb 01 '26 19:02

chappjc


Use this to get such a column vector, assuming A is the input matrix -

column_vector = A(eye(size(A))==0)

If you don't care about the order of the elements in the output, you can also use a combination of setdiff and diag -

column_vector = setdiff(A,diag(A))
like image 42
Divakar Avatar answered Feb 01 '26 18:02

Divakar