Matlab中两个字符串元胞数组的差异

发布于 2024-12-26 20:09:13 字数 492 浏览 4 评论 0原文

我有一个像这样的元胞数组

a={'potential'; 'impact'; 'of'; 'stranded'; 'assets'; 'and'; 'other'; 'necessary'; 'regulatory'; 'approvals'; 'assets'}

,想从中减去像 b={'a'; 这样的数组'和'; '的'; '我的'; '#'}。

计算差异后,使用 setdiff(a,b) 对数组进行排序。我想要的是从a中消除b中存在的所有元素而不对a进行排序。还应保留重复项,例如。数组 a 中的“资产”应出现在最终数组中的两个位置。

我使用的以下代码可以完成这项工作:

for i = 1:length(b)
    tf = ~strcmp(b(i),a)
    a = a(tf,:)
end

但问题是数组 b 包含超过 200 个字符串元素,这大大降低了我的代码速度。有更好的方法吗?

I have a cell array like

a={'potential'; 'impact'; 'of'; 'stranded'; 'assets'; 'and'; 'other'; 'necessary'; 'regulatory'; 'approvals'; 'assets'}

and want to subtract from it an array like b={'a'; 'and'; 'of'; 'my'; '#'}.

Using setdiff(a,b) sorts my array after the difference is computed. What I want is to eliminate from a all the elements present in b without sorting a. Also the repetitions should be preserved, for eg. 'assets' in array a should appear at two locations in final array.

The following code I am using does the job:

for i = 1:length(b)
    tf = ~strcmp(b(i),a)
    a = a(tf,:)
end

But the problem is that array b contains more than 200 string elements which slows down my code considerably. Is there a better way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

徒留西风 2025-01-02 20:09:14
tf = ismember(a,b);
a = a(~tf)
tf = ismember(a,b);
a = a(~tf)
烟柳画桥 2025-01-02 20:09:14
EDU>> a

a =     
    'potential'
    'impact'
    'of'
    'stranded'
    'assets'
    'and'
    'other'
    'necessary'
    'regulatory'
    'approvals'
    'assets'

EDU>> b

b = 

    'a'
    'and'
    'of'
    'my'
    '#'

 [I,J]=setdiff(a,b);

现在做

EDU>> a(sort(J),:)

ans = 

    'potential'
    'impact'
    'stranded'
    'other'
    'necessary'
    'regulatory'
    'approvals'
    'assets'
EDU>> a

a =     
    'potential'
    'impact'
    'of'
    'stranded'
    'assets'
    'and'
    'other'
    'necessary'
    'regulatory'
    'approvals'
    'assets'

EDU>> b

b = 

    'a'
    'and'
    'of'
    'my'
    '#'

 [I,J]=setdiff(a,b);

Now do

EDU>> a(sort(J),:)

ans = 

    'potential'
    'impact'
    'stranded'
    'other'
    'necessary'
    'regulatory'
    'approvals'
    'assets'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文