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

11 visualizaciones (últimos 30 días)
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!

Respuesta aceptada

Bruno Luong
Bruno Luong el 9 de Sept. de 2020
x = [3.75 22.95 2548.01 424.5]
[~,i] = min(abs(x-round(x)))

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by