如果您将第一个循环完全替换为:
,您将能够大大加快您的第一个循环:
labels = accumarray(ic, Y, [], @(y) mode(y));
第二个循环可以通过在Q(...) 中使用all(bsxfun(@eq, X_unique(i,:), P), 2) 来加速。这是一个很好的矢量化方法,假设您的数组不是非常大的 w.r.t。您机器上的可用内存。此外,为了节省更多时间,您可以使用在 P 上使用 X 所做的 unique 技巧,在更小的数组上运行所有比较:
[P_unique, ~, IC_P] = unique(P, 'rows', 'stable');
编辑:
以以下方式计算Q_unique:然后使用以下方法将其转换回完整数组:
Q_unique = zeros(length(P_unique),1);
for i = 1:length(X_unique)
Q_unique(all(bsxfun(@eq, X_unique(i,:), P_unique), 2)) = labels(i)
end
并转换回Q_full 以匹配原始P 输入:
Q_full = Q_unique(IC_P);
结束编辑
最后,如果内存是个问题,除了上述所有内容之外,您可能还希望在第二个循环中使用半向量化方法:
for i = 1:length(X_unique)
idx = true(length(P), 1);
for j = 1:size(X_unique,2)
idx = idx & (X_unique(i,j) == P(:,j));
end
Q(idx) = labels(i);
% Q(all(bsxfun(@eq, X_unique(i,:), P), 2)) = labels(i);
end
与bsxfun 相比,这将花费大约x3 的时间,但如果内存有限,那么您必须以速度付费。
另一个编辑
根据您的 Matlab 版本,您还可以通过将数字序列的文本表示映射到计算的 labels 来使用 containers.Map。请参见下面的示例。
% find unique members of X to work with a smaller array
[X_unique, ~, IC_X] = unique(X, 'rows', 'stable');
% compute labels
labels = accumarray(IC_X, Y, [], @(y) mode(y));
% convert X to cellstr -- textual representation of the number sequence
X_cellstr = cellstr(char(X_unique+48)); % 48 is ASCII for 0
% map each X to its label
X_map = containers.Map(X_cellstr, labels);
% find unique members of P to work with a smaller array
[P_unique, ~, IC_P] = unique(P, 'rows', 'stable');
% convert P to cellstr -- textual representation of the number sequence
P_cellstr = cellstr(char(P_unique+48)); % 48 is ASCII for 0
% --- EDIT --- avoiding error on missing keys in X_map --------------------
% find which P's exist in map
isInMapP = X_map.isKey(P_cellstr);
% pre-allocate Q_unique to the size of P_unique (can be any value you want)
Q_unique = nan(size(P_cellstr)); % NaN is safe to use since not a label
% find the labels for each P_unique that exists in X_map
Q_unique(isInMapP) = cell2mat(X_map.values(P_cellstr(isInMapP)));
% --- END EDIT ------------------------------------------------------------
% convert back to full Q array to match original P
Q_full = Q_unique(IC_P);
这需要大约 15 秒才能在我的笔记本电脑上运行。其中大部分被mode 的计算消耗。