Intersection of multiple arrays without for loop i

2019-06-24 06:33发布

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?:

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

2条回答
等我变得足够好
2楼-- · 2019-06-24 07:12

Here's another way. This also assumes there are no duplicates within each original vector.

tsCell_time = {[1 6 4 5] [4 7 1] [1 4 3] [4 3 1 7]}; %// example data (from Divakar)
t = [tsCell_time{:}]; %// concat into a single vector
u = unique(t); %// get unique elements
ind = sum(bsxfun(@eq, t(:), u), 1)==numel(tsCell_time); %// indices of unique elements
    %// that appear maximum number of times
result = u(ind); %// output those elements
查看更多
我只想做你的唯一
3楼-- · 2019-06-24 07:22

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))

Sample run -

>> 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
查看更多
登录 后发表回答