Rounding set of number to closest number in array
29 views (last 30 days)
Show older comments
Damir Kadyrzhan
on 9 Oct 2020
Commented: Ameer Hamza
on 9 Oct 2020
This is the data I need to round up to. Basically, each number from x_n I need them to get rounded up to closest number in yaxis array.
Y = round(x_n, yaxis) I have tried using this command but it says "The second input must be a real integer scalar." Then I have tried making a for loop putting each data separately, but I am struggling on what command to use to round it up to closest number from an array.
yaxis = [-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.60 0.8 1]
x_n = 0 0.5878 0.9511 0.9511 0.5878 0.0000 -0.5878 -0.9511 -0.9511 -0.5878 -0.0000
0.5878 0.9511 0.9511 0.5878 0.0000 -0.5878 -0.9511 -0.9511 -0.5878
Thank you for the help.
0 Comments
Accepted Answer
Ameer Hamza
on 9 Oct 2020
Edited: Ameer Hamza
on 9 Oct 2020
Following shows a general approach
yaxis = [-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.60 0.8 1];
x = [0 0.5878 0.9511 0.9511 0.5878 0.0000 -0.5878 -0.9511 -0.9511 -0.5878 -0.0000 0.5878 0.9511 0.9511 0.5878 0.0000 -0.5878 -0.9511 -0.9511 -0.5878];
[~, idx] = min(abs(x-yaxis.'));
x_rounded = yaxis(idx)
Since yaxis vector is regular, there might be a more efficient approach.
4 Comments
Ameer Hamza
on 9 Oct 2020
idx is the index number. It tells which element number in 'yaxis' is closest to the corresponding element in 'x'. You can run both lines one by one and see the output. It will help in understanding the code.
More Answers (2)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!