MATLAB中没有for循环的多个数组的交集
Intersection of multiple arrays without for loop in MATLAB
我一直被告知在 MATLAB 中几乎所有的 for 循环都可以省略,而且它们通常会减慢进程。那么这里有办法吗?:
我有一个元胞数组 (tsCell
)。 tsCell
存储不同长度的时间数组。我想为所有时间数组找到一个相交时间数组 (InterSection
):
InterSection = tsCell{1}.time
for i = 2:length{tsCell};
InterSection = intersect(InterSection,tsCell{i}.time);
end
这是使用 unique
and accumarray
的矢量化方法,假设输入元胞数组的每个元胞内没有重复项 -
[~,~,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
这是另一种方式。这还假设每个原始向量中没有重复项。
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
我一直被告知在 MATLAB 中几乎所有的 for 循环都可以省略,而且它们通常会减慢进程。那么这里有办法吗?:
我有一个元胞数组 (tsCell
)。 tsCell
存储不同长度的时间数组。我想为所有时间数组找到一个相交时间数组 (InterSection
):
InterSection = tsCell{1}.time
for i = 2:length{tsCell};
InterSection = intersect(InterSection,tsCell{i}.time);
end
这是使用 unique
and accumarray
的矢量化方法,假设输入元胞数组的每个元胞内没有重复项 -
[~,~,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
这是另一种方式。这还假设每个原始向量中没有重复项。
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