MATLAB中没有for循环的多个数组的交集 [英] Intersection of multiple arrays without for loop in MATLAB

查看:171
本文介绍了MATLAB中没有for循环的多个数组的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直被告知,在MATLAB中可以省略几乎所有的for循环,并且它们通常会减慢该过程.那么这里有办法吗?:

I've always been told that almost all for loops can be omitted in MATLAB and that they in general slow down the process. So is there a way to do so here?:

我有一个单元格数组(tsCell). tsCell存储长度可变的时间数组.我想为所有时间数组(InterSection)找到一个相交的时间数组:

I have a cell-array (tsCell). tsCell stores time-arrays with varying length. I want to find an intersecting time-array for all time-arrays (InterSection):

InterSection = tsCell{1}.time
for i = 2:length{tsCell};
    InterSection = intersect(InterSection,tsCell{i}.time);
end

推荐答案

这是使用 accumarray ,假设在输入像元数组的每个像元中没有重复-

Here's a vectorized approach using unique and accumarray, assuming there are no duplicates within each cell of the input cell array -

[~,~,idx] = unique([tsCell_time{:}],'stable')
out = tsCell_time{1}(accumarray(idx,1) == length(tsCell_time))

样品运行-

>> tsCell_time = {[1 6 4 5],[4 7 1],[1 4 3],[4 3 1 7]};

>> InterSection = tsCell_time{1};
for i = 2:length(tsCell_time)
    InterSection = intersect(InterSection,tsCell_time{i});
end
>> InterSection
InterSection =
     1     4

>> [~,~,idx] = unique([tsCell_time{:}],'stable');
out = tsCell_time{1}(accumarray(idx,1) == length(tsCell_time));
>> out
out =
     1     4

这篇关于MATLAB中没有for循环的多个数组的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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