Effacer les filtres
Effacer les filtres

find the nearest value

75 vues (au cours des 30 derniers jours)
crispin Donnelly
crispin Donnelly le 22 Août 2013
Hi!
Can someone help with this problem please.....
if for example, q = [1 3 6 8 10 15]
find(q==8) returns ans = 4
find(q==9) returns Empty matrix: 1-by-0 because there is no value 9
...how do I query, find the value in q that is nearest to 9??

Réponse acceptée

Iain
Iain le 22 Août 2013
q = [1 3 6 8 10 15];
v = 9;
[~,ans] = (min(abs(q - v)))
  1 commentaire
crispin Donnelly
crispin Donnelly le 22 Août 2013
nice! thanks

Connectez-vous pour commenter.

Plus de réponses (1)

mohamed azuan wahari
mohamed azuan wahari le 9 Mai 2016
Modifié(e) : Walter Roberson le 9 Mai 2016
find nearest value on matrix
Can someone help with this problem please.....
for example
a= 1250
matrix_b=[98 125 945 1005;
105 204 1105 1249;
200 250 1299 1450;
300 450 1350 1850]
want to find nearest equal or greater than a=1250
and the answer should be 1299
  2 commentaires
Walter Roberson
Walter Roberson le 9 Mai 2016
v = sort(matrix_b(:));
vidx = floor(interp1(v, 1:length(v), a, 'linear', 'extrap'));
if vidx ~= 0
result = b(vidx);
end
Or
v = sort(matrix_b(:));
vidx = find(v >= a, 1, 'first');
if ~isempty(vidx)
result = v(vidx);
end
or
v = sort(matrix_b(:));
[~, vidx] = histc(a, v);
if vidx ~= 0
result = v(vidx);
end
The middle of these is probably the easiest to think about, but it cannot be generalized to a list of a values like the other ones can (aside from the testing to be sure that a result was found.)
Walter Roberson
Walter Roberson le 9 Mai 2016
If you have R2016a or later, then
v = sort(matrix_b(:));
result = interp1(v, v, a, 'previous');

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by