Rounding set of number to closest number in array

29 views (last 30 days)
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.

Accepted Answer

Ameer Hamza
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
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.
Ameer Hamza
Ameer Hamza on 9 Oct 2020
@Image Analyst, thanks for your suggestions.

Sign in to comment.

More Answers (2)

Fangjun Jiang
Fangjun Jiang on 9 Oct 2020
interp1(yaxis,yaxis,x_n,'nearest')

Mathieu NOE
Mathieu NOE on 9 Oct 2020
hello
I think this function should do the job
all the best

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!