string - 单元格单元格数组的并集

标签 string matlab cell union

我正在寻找合并字符串元胞数组的两个元胞数组的方法。例如:

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/

相关文章:

matlab - 具有解边界的 fsolve

matlab - 使用非齐次隐马尔可夫模型预测降雨量

ios - 自定义类的 TableView 单元格返回 nil

c# - 如何从字符串中删除字符组合?

matlab - matlab的opencv模块无法正常工作

php - 为什么字符串在 PHP 5.3 中表现得像数组?

vb.net 将 datagridview 列类型更改为组合框

c# - 无法使用 itextsharp 垂直对齐表格单元格中的文本

python - 为什么 'int"在 Python 中不可迭代,但 'str' 是?

c - 如何为 %20s 的 scanf 删除额外输入