6

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.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Jill
  • 69
  • 3

2 Answers2

7

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • It's as simple as that! Thank you very much! – Jill Nov 15 '15 at 13:01
  • Why the transpose? I can see that it works by testing, but the `~eye` makes a mask over the original `x` as far as I can see. Does the second line of code use linear indices in column-major order? – Adriaan Nov 15 '15 at 13:55
  • 2
    The first transpose is because the OP wants the result returned row major but indexing with `~eye(size(x))` returns column major. The second transpose is because the OP wants a row vector instead of a column vector that is returned by the logical mask. – IKavanagh Nov 15 '15 at 14:07
1

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
Divakar
  • 218,885
  • 19
  • 262
  • 358