


RESCALE Rescales a data set. [VALUESOUT, OLDMIN, OLDMAX] = RESCALE(VALUESIN, NEWMIN, NEWMAX), given a VALUESIN array of arbitrary dimension, will return a VALUESOUT of the same size and linearly rescaled to the range NEWMIN:NEWMAX. The minimum and maximum values of the original matrix are also returned. Note: if VALUESIN contains only a single value, the scaled output will be set to (NEWMIN + NEWMAX) / 2.


0001 function [values, oldmin, oldmax] = rescale(values, newmin, newmax) 0002 %RESCALE Rescales a data set. 0003 % [VALUESOUT, OLDMIN, OLDMAX] = RESCALE(VALUESIN, NEWMIN, NEWMAX), given 0004 % a VALUESIN array of arbitrary dimension, will return a VALUESOUT of 0005 % the same size and linearly rescaled to the range NEWMIN:NEWMAX. The 0006 % minimum and maximum values of the original matrix are also returned. 0007 % 0008 % Note: if VALUESIN contains only a single value, the scaled output will 0009 % be set to (NEWMIN + NEWMAX) / 2. 0010 0011 extrema = minmax(values); 0012 oldmin = extrema(1); oldmax = extrema(2); 0013 0014 oldrange = oldmax - oldmin; 0015 newrange = newmax - newmin; 0016 0017 % special case 0018 if (oldrange == 0) 0019 values = repmat((newmax + newmin)/2, size(values)); 0020 return; 0021 end 0022 0023 % Rescaling conceptually uses the following formula: 0024 % zero_to_one = (oldvalues - oldmin) ./ oldrange; 0025 % newvalues = (zero_to_one .* newrange) + newmin; 0026 % But doing it out longhand like this takes two matrix multiplications 0027 % and two matrix additions. The command below takes a more convoluted 0028 % route to do the same thing with half the number of full matrix operations. 0029 scale = oldrange ./ newrange; 0030 shift = oldmin - (scale .* newmin); 0031 values = (values - shift) ./ scale;