How to round a value to the nearest value in an array?
Afficher commentaires plus anciens
I have a large matrix of orientation values from an image and want to round them to the nearest value from an array.
What I have right now is a very long and overly complicated if/else statement that looks like this:
array = [0, 45, 90, 135];
if ((value(x, y) >= 0 && value(x, y) < 22.5) || (value(x, y) >= 157.5 && value(x, y) < 202.5) || (value(x, y) >= 337.5) && (value(x, y) <= 360))
value(x, y) = array(1);
elseif ((value(x, y) >= 22.5) && (value(x, y) < 67.5) || (value(x, y) >= 202.5) && (value(x, y) < 247.5))
value(x, y) = array(2);
...
end
What I would like is something that resembles more the following, or any MATLAB type shortcut:
array = [0, 45, 90, 135];
value(x, y) = roundToNearest(value(x, y), array);
Réponses (2)
Ameer Hamza
le 10 Nov 2020
You can use interp1() with 'nearest'
array = [0, 45, 90, 135];
value; % matrix
value_rounded = interp1(array, array, value, 'nearest', 'extrap')
Bjorn Gustavsson
le 10 Nov 2020
At the file exchange I quickly found a couple of contributions that allows rounding to some desired precision. For this case could you use something like:
y_rounded = 45*round(y_values/45);
HTH
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!