Intersection of multiple arrays without for loop in MATLAB

感情迁移 提交于 2019-12-23 12:23:03

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/35825435/intersection-of-multiple-arrays-without-for-loop-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!