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.
0 个评论
采纳的回答
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
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 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!