在Matlab中测试某些元素和/或列的相等性 [英] Test the equality of some elements and/or columns in matlab

查看:128
本文介绍了在Matlab中测试某些元素和/或列的相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个矩阵:

$ X $ =

 1     2     3
 4     5     6
 7     8     9

$ Y $ =

 1    10    11
 4    12    13
 7    14    15

我知道,如果我想在$ X $或$ Y $中找到特定元素的索引,则可以使用函数"find".例如:$ index_3 = find(X == 3)$.

I know that if I want to find the index of a specific element in $X$ or $Y$, I can use the function ''find''. For example: $index_3 = find(X==3)$.

1)我的第一个问题是,如何才能找到(或测试)$ X $是否包含某些也存在于$ Y $中的元素?我可以使用查找"功能吗?如果可以,怎么办?

1) My first question is how can i find (or test) if $X$ contains some elements that are also present in $Y$? can I use the function ''find''? if yes so how?

2)第二个问题与第一个有关.现在,我想查找(或测试)$ Y $中是否也存在$ X $中的某些列.例如,如何在matlab中证明$ X $中的列[[1; 2; 3] $也出现在$ Y $中?

2) The second question is related to the first. Now I want to find (or test) if some columns in $X$ are also present in $Y$. For example, how can I demonstrate in matlab that the column $[1;2;3]$ in $X$ is also present in $Y$?

任何帮助将不胜感激.

Any help will be very appreciated.

推荐答案

您可以使用 ismember .对于第一个,它就是:

You can do both of these with ismember. For the first one, it's simply:

locsX = ismember(X, Y);

对于您的测试矩阵,这可以为您提供:

For your test matrices this gives you:

locsX =

   1   0   0
   1   0   0
   1   0   0

例如:

X =

   1   2   3
   4   5   6
   7   8   9

Z =

    1    7   13
    3    9   15
    5   11   17

>> ismember(X, Z)
ans =

   1   0   1
   0   1   0
   1   0   1

对于问题的第二部分,ismember具有用于比较的可选标志:

For the second part of your question, ismember has an optional flag to compare rows:

rowsX = ismember(X, Y, 'rows');

所以要获取列,只需对两个矩阵进行转置:

so to get the columns, just take the transpose of both matrices:

rowsX = ismember(X.', Y.', 'rows')

rowsX =

   1
   0
   0

这篇关于在Matlab中测试某些元素和/或列的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆