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

10 ビュー (過去 30 日間)
noMathWiz
noMathWiz 2020 年 9 月 9 日
コメント済み: noMathWiz 2020 年 9 月 9 日
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!

採用された回答

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by