Intersecting multiple arrays without a loop in MATLAB

I've always been told that almost everything for loops can be omitted in MATLAB and that they generally slow down the process. So, is there a way to do this here:

I have an array of cells ( tsCell). tsCellstores variable length arrays of time. I want to find a intersecting time array for all temporary arrays ( InterSection):

InterSection = tsCell{1}.time
for i = 2:length{tsCell};
    InterSection = intersect(InterSection,tsCell{i}.time);
end
+4
source share
2 answers

Here we use a vector approach using uniqueand accumarrayif there are no duplicates in each cell of the array of input cells -

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

Run Example -

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

. , .

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

All Articles