2

I'm trying to select some elements by using boolean operations in MATLAB.

I have A = [1 2 3; 4 5 6; 7 8 9]

A =

 1     2     3
 4     5     6
 7     8     9

When using A([true true false; true true false]) I get:

 1
 4
 7
 2

Isn't it supposed to be?:

 1
 4
 2
 5

Does anyone know what's going on?

horchler
  • 18,384
  • 4
  • 37
  • 73
Bella Ma
  • 21
  • 1

1 Answers1

0

See this example for the documentation on logical indexing. It may not be explained as clearly as it should, but if you specify a logical index with fewer elements that then the indexed matrix (A) then the indexing matrix is linearized such that:

A = [1 2 3; 4 5 6; 7 8 9];
idx1 = [true true false; true true false];
A(idx1)

is equivalent to:

idx1 = [true true false; true true false];
A(idx1(:))

In other words, the index matrix (idx1) elements specify the output in column-wise order.

If you want what you though you should get, you can use:

idx2 = [true false true; true true false];
A(idx2)

or you can transform your original index array:

idx1 = [true true false; true true false];
idx2 = reshape(idx1.',2,3);
A(idx2)

or just use:

idx3 = [true true false true true].';
A(idx3)
horchler
  • 18,384
  • 4
  • 37
  • 73