我总是被告知几乎所有for循环都可以在MATLAB中省略,并且它们通常会减慢过程。那么有没有办法这样做?:
我有一个单元格数组(tsCell
)。 tsCell
存储长度不同的时间数组。我想为所有时间数组(InterSection
)找到一个相交的时间数组:
InterSection = tsCell{1}.time
for i = 2:length{tsCell};
InterSection = intersect(InterSection,tsCell{i}.time);
end
答案 0 :(得分:3)
这是另一种方式。这也假设每个原始向量中没有重复。
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
答案 1 :(得分:2)
这是使用unique
和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