这是给你的单线:
sum(bsxfun(@times, bsxfun(@eq, M, reshape(A,1,1,[])), reshape(B,1,1,[])), 3)
它相当快。
基准
这是基准测试代码:
%// bsxfun party
tic
for k = 1:10000
M1 = sum(bsxfun(@times,bsxfun(@eq,M,reshape(A,1,1,[])),reshape(B,1,1,[])),3);
end
toc
%// Using ismember
tic
for k = 1:10000
[idx,b] = ismember(M,A);
M(idx) = B(b(idx));
end
toc
%// Using a simple loop
tic
for k = 1:10000
M1 = M;
for t = 1:length(A)
M1(M == A(t)) = B(t);
end
end
toc
结果是:
Elapsed time is 0.030135 seconds.
Elapsed time is 0.094354 seconds.
Elapsed time is 0.007410 seconds.
所以这个单线比优雅的解决方案更快ismember
,但简单的(JIT 加速)循环胜过两者。令人惊讶,不是吗?:)