Elegant vectorized version of CHANGEM (substitute

2020-07-10 03:51发布

问题:

In Matlab 2012b, there is a changem function that allows you to substitute elements of a matrix with other values specified by a set of keys: Substitute values in data array

Is there an elegant/vectorized way to do the same if I don't have the Mapping toolbox?

回答1:

Yes, use ismember:

A       = magic(3);
oldCode = [ 8  9];
newCode = [12 13];

[a,b] = ismember(A,oldCode);

A(a) = newCode(b(a));

I don't know changem, and I suspect the above will not fully cover its functionality (why else would TMW have introduced changem?), but well, it does what you asked :)



回答2:

Vectorized implementation of CHANGEM with bsxfun, max

Sometime back, I was made to write a customized vectorized version of changem implemented with bsxfun and max as part of a much bigger problem. The referenced solution could be found here. Then, following few links I saw this post and thought it could be posted here as a solution for an easy find among future readers as also because this problem exclusively asks for an efficient and vectorized version of changem. So, here's the function code -

%// CHANGEM_VECTORIZED  Vectorized version of CHANGEM with MAX, BSXFUN
function B  = changem_vectorized(A,newval,oldval)

B = A;
[valid,id] = max(bsxfun(@eq,A(:),oldval(:).'),[],2); %//'
B(valid) = newval(id(valid));

return;

The syntax used in the custom version follows the same syntax as in changem.m -

function B = changem(A, newval, oldval)
%CHANGEM  Substitute values in data array ... 


回答3:

Unfortunately, I think you need a FOR loop. But it's pretty straightforward:

function xNew = myChangeM(x,oldCode,newCode)
% xNew = myChangeM(x,oldCode,newCode)
%
%   x is a matrix of vaues
%    oldCode and newCode specify the values to replace and with what
% e.g., 
%   x = round(randn(10));
%   oldCode = [-1 -2]; 
%   newCode = [nan, 10]; %replace -1 with nan, -2 by 10
% xNew = myChangeM(x,oldCode,newCode)

xNew = x;
for repInd = 1:numel(oldCode)
    xNew(x == oldCode(repInd)) = newCode(repInd); 
end