Find index of a nearest value
30 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Adi Purwandana
le 17 Juin 2024
Réponse apportée : Voss
le 17 Juin 2024
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
0 commentaires
Réponse acceptée
Matlab Pro
le 17 Juin 2024
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(:))
Plus de réponses (3)
Image Analyst
le 17 Juin 2024
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))
closestValue = x(index)
0 commentaires
Voss
le 17 Juin 2024
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)
closest = x(idx)
0 commentaires
Pratyush
le 17 Juin 2024
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);
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!