Ghazwan Alsoufi
Ghazwan Alsoufi

Reputation: 63

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?

Upvotes: 2

Views: 110

Answers (4)

Luis Mendo
Luis Mendo

Reputation: 112659

Assuming that the matrix is square,

v = A(mod(0:numel(A)-1, size(A,1)+1) > 0).';

Upvotes: 0

chappjc
chappjc

Reputation: 30579

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

Upvotes: 3

rayryeng
rayryeng

Reputation: 104474

You can also use linear indexing to access the diagonal elements and null them. This will automatically reshape itself to a single vector:

A(1:size(A,1)+1:end) = [];

Bear in mind that this will mutate the original matrix A. If you don't want this to happen, make a copy of your matrix then perform the above operation on that copy. In other words:

Acopy = A;
Acopy(1:size(A,1)+1:end) = [];

Acopy will contain the final result. You need to create a vector starting from 1 and going to the end in increments of the rows of the matrix A added with 1 due to the fact that linear indices are column-major, so the linear indices used to access a matrix progress down each row first for a particular column. size(A,1) will allow us to offset by each column and we add 1 each time to ensure we get the diagonal coefficient for each column in the matrix.

Upvotes: 3

Divakar
Divakar

Reputation: 221524

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))

Upvotes: 3

Related Questions