Rounding set of number to closest number in array

20 次查看(过去 30 天)
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.

采纳的回答

Ameer Hamza
Ameer Hamza 2020-10-9
编辑:Ameer Hamza 2020-10-9
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 个评论
Ameer Hamza
Ameer Hamza 2020-10-9
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.

请先登录,再进行评论。

更多回答(2 个)

Fangjun Jiang
Fangjun Jiang 2020-10-9
interp1(yaxis,yaxis,x_n,'nearest')

Mathieu NOE
Mathieu NOE 2020-10-9
hello
I think this function should do the job
all the best

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by