简体   繁体   English

使用matlab选择矩阵中的元素

[英]Selecting elements in matrix using matlab

My problem is this: I've a matrix, as example 我的问题是:我有一个矩阵,例如

1   2   3 
4   2   6
6   1   8
4   5   4
7   1   5
8   2   0

I wish to extract selected values from the matrix, as example, a vector like this 我希望从矩阵中提取选定的值,例如,像这样的向量

B = [3 6 0]

selecting third column values when the value in the second column is 2. I tried in different ways, but no one of these works. 当第二列中的值为2时选择第三列值。我尝试了不同的方法,但没有一个工作。

用这个 -

B = A(A(:,2)==2,3)' %// Assuming A is your input matrix

If M is your Matrix, you can select the second column using 如果M是您的Matrix,您可以使用选择第二列

M(:,2)

Compare it to two to get the lines which contain a 2 将它与两个比较得到包含2的行

M(:,2)==2

And use this logical vector to select your elements from the third column. 并使用此逻辑向量从第三列中选择元素。

M(M(:,2)==2,3)

A little more generally: if you want to select based on a set of values, use ismember to generate the logical index: 更一般地说:如果要根据一组值进行选择,请使用ismember生成逻辑索引:

>> A(ismember(A(:,2), [2 5]) , 3) %// [2 5]: values you want to find in 2nd col

ans =

     3
     4
     6
     0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM