One solution:
old = [1,2,3,4,5,6,7,8,9];
new = [11,12,13,21,22,23,31,32,33];
[found, idx] = ismember(TheNumbers, [1,2,3,4,5,6,7,8,9]);
replaced_numbers = TheNumbers;
replaced_numbers(found) = new(idx(found));
But in the case where the old series is consecutive integers:
oldmin = 1; oldmax = 9;
new = [11,12,13,21,22,23,31,32,33];
mask = TheNumbers >= oldmin & TheNumbers <= oldmax;
replaced_numbers = TheNumbers;
replaced_numbers(mask) = new(TheNumbers(mask)-oldmin+1);
Another approach, especially if you know the range of values ahead of time and they are integers:
LUT = cast(0 : maximum_possible_input, class(TheNumbers));
LUT(1+(1:10)) = [11,12,13,21,22,23,31,32,33];
replaced_numbers = LUT(double(TheNumbers)+1);
This version of the code assumes that TheNumbers might be an integer data type that includes 0, such as uint8 . The double(TheNumbers) is needed because uint8(255)+1 would saturate to 255 whereas we need 255 to map to 256 because we have to shift index by 1 to allow for 0.
In the special case where the inputs are integer but never include 0:
LUT = cast(1 : maximum_possible_input, class(TheNumbers))
LUT(1:10) = [11,12,13,21,22,23,31,32,33];
replaced_numbers = LUT(TheNumbers);
1 Comment
Direct link to this comment
https://se.mathworks.com/matlabcentral/answers/179205-mapping-numbers-to-another-number#comment_267121
Direct link to this comment
https://se.mathworks.com/matlabcentral/answers/179205-mapping-numbers-to-another-number#comment_267121
Sign in to comment.