Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: Remove diagonal from matrix and reform

I would like to remove the diagonal of the following matrix;

 [0 1 1
  0 0 0
  0 1 0]

and put this in a vector as such

[1 1 0 0 0 1]

Is there a one-way function to do this? Most other solutions I found on Stack Overflow delete all zeros.

like image 643
Jill Avatar asked Nov 15 '15 12:11

Jill


2 Answers

If two lines are fine...

x = x.'; %'// transpose because you want to work along 2nd dimension first
result = x(~eye(size(x))).'; %'// index with logical mask to remove diagonal
like image 127
Luis Mendo Avatar answered Sep 22 '22 05:09

Luis Mendo


Here's an almost one-liner -

[m,n] =  size(x);
x(setdiff(reshape(reshape(1:numel(x),m,n).',1,[]),1:m+1:numel(x),'stable'))

And I will put up my fav bsxfun here -

xt = x.';    %//'
[m,n] =  size(x);
out = xt(bsxfun(@ne,(1:n)',1:m)).'

Sample run -

>> x
x =
    52    62    37    88
    23    68    98    91
    49    40     4    79
>> [m,n] =  size(x);
>> x(setdiff(reshape(reshape(1:numel(x),m,n).',1,[]),1:m+1:numel(x),'stable'))
ans =
    62    37    88    23    98    91    49    40    79
>> xt = x.';
>> xt(bsxfun(@ne,(1:n)',1:m)).'
ans =
    62    37    88    23    98    91    49    40    79
like image 40
Divakar Avatar answered Sep 24 '22 05:09

Divakar