在MATLAB中替换矩阵值

bop*_*bop 2 arrays matlab replace

我有一个矩阵,如

M = [ 1 3 2 4;
      3 3 2 1;
      2 4 1 3]
Run Code Online (Sandbox Code Playgroud)

有一个基地 A = [ 1 2 3 4];

我还有另一个基地 B = [103 104 105 106];

我需要用M中的B值替换A的值.所以我的新M应该是:

M1 = [ 103  105 104 106;
       105  105 104 103;
       104  106 103 105];
Run Code Online (Sandbox Code Playgroud)

元素是随机数,所以我需要在A和B之间使用indice一对一连接.我应该提一下吗?当然不是为了LOOPS:D谢谢

Eit*_*n T 6

这是你的单行:

sum(bsxfun(@times, bsxfun(@eq, M, reshape(A,1,1,[])), reshape(B,1,1,[])), 3)
Run Code Online (Sandbox Code Playgroud)

它相当快.

基准

这是基准测试代码:

%// 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
Run Code Online (Sandbox Code Playgroud)

结果是:

Elapsed time is 0.030135 seconds.
Elapsed time is 0.094354 seconds.
Elapsed time is 0.007410 seconds.
Run Code Online (Sandbox Code Playgroud)

因此,这种单线程比优雅的解决方案更快ismember,但简单(JIT加速)循环击败了两者.令人惊讶,不是吗?:)