Elegant vector version of CHANGEM (wildcard values) - MATLAB

Matlab 2012b has a changem function that allows you to substitute matrix elements with other values โ€‹โ€‹specified by a key set: Replace values โ€‹โ€‹in a data array

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

+7
source share
3 answers

Yes, use ismember :

 A = magic(3); oldCode = [ 8 9]; newCode = [12 13]; [a,b] = ismember(A,oldCode); A(a) = newCode(b(a)); 

I do not know changem , and I suspect that the above will not fully cover its functionality (why else did TMW introduce changem ?), But, well, it does what you requested :)

+11
source

Vectorized implementation of CHANGEM with bsxfun , max

Once CHANGEM a time, I was created to write a custom vector version of CHANGEM implemented with bsxfun and max as part of a much more serious problem. Reference solution can be found here . Then, after several links, I saw this post and thought that it could be published here as a solution for easy finding among future readers, and also because this problem exclusively requires an effective and vectorized version of CHANGEM . So here the function code is -

 %// 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 user version follows the same syntax as in changem.m -

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

Unfortunately, I think you need a FOR loop. But it is quite simple:

 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 % eg, % 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 
+1
source

All Articles