Find index of a nearest value

30 次查看(过去 30 天)
Hello there,
If I have a data: x = [1 2 3 4 5 6 11 15 21 51 52 54 100 101 151 201 251 301 401];
Anyone knows how to get the index of the value close to a certain values: 10, 20, 50, 100, 150, 200, 250, 300, 400?
In this case, the index should be related to the x = 11, 21, etc.
thanks

采纳的回答

Matlab Pro
Matlab Pro 2024-6-17
A simple slution using dsearchn
x = [1 2 3 4 5 6 11 15 21 51 52 54 100 101 151 201 251 301 401];
vals = [10, 20, 50, 100, 150, 200];
dsearchn(x(:),vals(:))
ans = 6x1
7 9 10 13 15 16
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

更多回答(3 个)

Image Analyst
Image Analyst 2024-6-17
Another solution
x = [1 2 3 4 5 6 11 15 21 51 52 54 100 101 151 201 251 301 401];
targetValue = 10;
[~, index] = min(abs(x - targetValue))
index = 7
closestValue = x(index)
closestValue = 11

Voss
Voss 2024-6-17
x = [1 2 3 4 5 6 11 15 21 51 52 54 100 101 151 201 251 301 401];
target = [10, 20, 50, 100, 150, 200, 250, 300, 400];
[~,idx] = min(abs(x(:)-target(:).'),[],1)
idx = 1x9
7 9 10 13 15 16 17 18 19
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
closest = x(idx)
closest = 1x9
11 21 51 100 151 201 251 301 401
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Pratyush
Pratyush 2024-6-17
Hi Adi,
The following script should help you find the indices of values closest to given numbers in an array.
% Your data
x = [1 2 3 4 5 6 11 15 21 51 52 54 100 101 151 201 251 301 401];
% The target values you want to find the closest in x
targets = [10, 20, 50, 100, 150, 200, 250, 300, 400];
% Preallocate the array for indices
indices = zeros(size(targets));
% Loop through each target value
for i = 1:length(targets)
% Calculate the absolute differences
[~, indices(i)] = min(abs(x - targets(i)));
end
% Display the indices
disp(indices);

类别

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

标签

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by