如何在Matlab中使用布尔矩阵选择元素

时间:2016-04-03 22:08:21

标签: matlab matrix indexing

我试图通过在MATLAB中使用布尔运算来选择一些元素。

我有A = [1 2 3; 4 5 6; 7 8 9]

A =

 1     2     3
 4     5     6
 7     8     9

使用A([true true false; true true false])时,我得到:

 1
 4
 7
 2

它不应该是吗?:

 1
 4
 2
 5

有谁知道发生了什么?

1 个答案:

答案 0 :(得分:0)

有关this example的文档,请参阅logical indexing。它可能没有像它应该那样清楚地解释,但是如果你指定一个逻辑索引,其中元素少于索引矩阵(A),那么索引矩阵将被线性化,以便:

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

相当于:

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

换句话说,索引矩阵(idx1)元素按列顺序指定输出。

如果你想要你应该得到的东西,你可以使用:

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

或者您可以转换原始索引数组:

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

或只是使用:

idx3 = [true true false true true].';
A(idx3)