2016-04-03 212 views
2

我想通过在MATLAB中使用布尔运算来选择一些元素。如何使用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 

有谁知道这是怎么回事?

回答

0

有关logical indexing的文档,请参阅this example。它可能不会很清楚,因为它应该进行说明,但如果指定与然后索引矩阵(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)