How to find the index of a non-integer array with closest value to any integer?

5 views (last 30 days)
Given an array of non-integers, how can you find which value in that array is closest to an integer (any integer)?
Example (1): Given an array, x, find the index where x is closest to an integer.
x = [3.75 22.95 2548.01 424.5]
Answer: x(3) is closest to an integer (it is 0.01 away from the integer 2548).
Example 2: Given an array, "a," find where "a" is closest to an integer.
% Define constants
theta = linspace(0,90,900000);
d = 0.02;
l = 632.8e-9;
% create the 1-D non-integer array
a = (2.*d.*cosd(theta))./l;
% Double check to see if there are any integers in the array "a"
finds = find(array == floor(a)); % there are no integers -- "a" is all non-integers, which is why I need your help
Answer: I don't know and need your help!

Accepted Answer

Bruno Luong
Bruno Luong on 9 Sep 2020
x = [3.75 22.95 2548.01 424.5]
[~,i] = min(abs(x-round(x)))

More Answers (0)

Categories

Find more on Matrices and Arrays 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!