gpt4 book ai didi

arrays - 如何使用 MATLAB 返回包含 list1 和 list2 中的元素的列表

转载 作者:太空宇宙 更新时间:2023-11-03 20:33:24 26 4
gpt4 key购买 nike

我试图在 MATLAB 中比较 list1list2 并获得第三个列表 list3,其中包含 list1 中的所有元素 也在 list2 中(包括 list1 中的重复条目)。

例如,list1包含元素

AA,AB,AC,AC,AC,CB 

list2以下几个:

BA,BB,AC,BN,MN,CB,CB

因此,list3应该包含

AC,AC,AC,CB

因为 AC 可以在 list1 中出现三次,它也必须在 list3 中出现三次。 CBlist2 中出现两次,但在 list1 中只出现一次,因此它在 list3 中应该只显示一次。

我如何在 MATLAB 中执行此操作?

最佳答案

您可以使用 ismember为此。

tf = ismember(A, S) returns an array the same size as A, containing logical 1 (true) where the elements of A are in the set S, and logical 0 (false) elsewhere. In set theory terms, k is 1 where AS. Inputs A and S can be numeric or character arrays or cell arrays of strings.

如果将 list1list2 定义为元胞数组,它将变成这样:

list1 = {'AA', 'AB', 'AC', 'AC', 'AC', 'CB'}
list2 = {'BA', 'BB', 'AC', 'BN', 'MN', 'CB', 'CB'}
I = ismember(list1, list2) % positions where the elements of list1 are in the set list2
list3 = list1(ismember(list1, list2))

它将返回:

I =     0     0     1     1     1     1
list3 = 'AC' 'AC' 'AC' 'CB'

您还可以将列表(集合)定义为矩阵(如果集合中的所有元素都具有相同的长度)。在这种情况下,您需要将另一个参数传递给 ismember

tf = ismember(A, S, 'rows'), when A and S are matrices with the same number of columns, returns a vector containing 1 where the rows of A are also rows of S and 0 otherwise. You cannot use this syntax if A or S is a cell array of strings.

list1 = ['AA'; 'AB'; 'AC'; 'AC'; 'AC'; 'CB']
list2 = ['BA'; 'BB'; 'AC'; 'BN'; 'MN'; 'CB'; 'CB']
I = ismember(list1, list2, 'rows')
list3 = list1(ismember(list1, list2, 'rows'), :)

返回:

I =
0
0
1
1
1
1


list3 =
AC
AC
AC
CB

关于arrays - 如何使用 MATLAB 返回包含 list1 和 list2 中的元素的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38416054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com