Elegant vectorized version of CHANGEM (substitute values) - MATLAB

时间秒杀一切 提交于 2019-12-21 12:27:12

问题


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


来源:https://stackoverflow.com/questions/13812656/elegant-vectorized-version-of-changem-substitute-values-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!