我正在寻找合并字符串元胞数组的两个元胞数组的方法。例如:
A = {{'one' 'two'};{'three' 'four'};{'five' 'six'}};
B = {{'five' 'six'};{'seven' 'eight'};{'nine' 'ten'}};
我想得到类似的东西:
C = {{'one' 'two'};{'three' 'four'};{'five' 'six'};{'seven' 'eight'};{'nine' 'ten'}};
但是当我使用 C = union(A, B)
时,MATLAB 返回一条错误消息:
Input A of class cell and input B of class cell must be cell arrays of strings, unless one is a string.
有谁知道如何以一种希望简单的方式做这样的事情?我将不胜感激。
备选方案:以除字符串元胞数组的元胞数组之外的任何其他方式拥有分隔字符串元胞数组的方法也很有用,但据我所知,这是不可能的。
谢谢!
最佳答案
C=[A;B]
allWords=unique([A{:};B{:}])
F=cell2mat(cellfun(@(x)(ismember(allWords,x{1})+2*ismember(allWords,x{2}))',C,'uni',false))
[~,uniqueindices,~]=unique(F,'rows')
C(sort(uniqueindices))
我的代码做了什么:它构建了一个包含所有单词的列表 allwords
,然后这个列表用于构建一个矩阵,其中包含行之间的相关性以及它们包含的单词。 1=第一个词匹配,2=第二个词匹配。最后,可以在这个数字矩阵上应用 unique
来获取索引。
包括我的更新,现在每个单元格的 2 个单词是硬编码的。要摆脱此限制,替换匿名函数 (@(x)(ismember(allWords,x{1})+2*ismember(allWords,x{2}))
是不必要的) 具有更通用的实现。可能又要用 cellfun 了。
关于string - 单元格单元格数组的并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23835840/