Effacer les filtres
Effacer les filtres

Is it possible to do a search in a table for a value nearest to a number I want?

2 vues (au cours des 30 derniers jours)
Rachel Ong
Rachel Ong le 20 Mar 2022
Modifié(e) : Torsten le 20 Mar 2022
If I have an array of 100x2, is it possible to find the index of the row number nearest to a number I want? For example something simple like this? Then if I have 2 numbers that are equally close to each other like the one below, will it be possible do a search criteria in the second column using a loop or something?
array = [1 3;
2 4;
5 4;
7 10;
9 3;
100 12;
44 22;
65 11;
77 3]
search_num = 8
What can I do to this array to get the index nearest to 8 and if there are numbers that are equally close I want the number with a lower number in the second column.
Any help would be appreciated. Thank you.

Réponses (2)

Star Strider
Star Strider le 20 Mar 2022
Your quesiton is a bit ambiguous, so I am not certain what result you want.
Try this —
array = [1 3;
2 4;
5 4;
7 10;
9 3;
100 12;
44 22;
65 11;
77 3];
search_num = 8;
idx = find(array(:,1) <= search_num); % Index Of Closest Result In 'array(:,2)'
Out = array(idx,:)
Out = 4×2
1 3 2 4 5 4 7 10
[~,idx] = min(Out(:,2));
Result = Out(idx,:)
Result = 1×2
1 3
.

Torsten
Torsten le 20 Mar 2022
Modifié(e) : Torsten le 20 Mar 2022
array = [1 3;
2 4;
5 4;
7 10;
9 3;
100 12;
44 22;
65 11;
77 3];
search_num = 8;
idx1 = find(abs(array(:,1)-search_num) == min(abs(array(:,1)-search_num)));
idx2 = find(array(idx1,2) == min(array(idx1,2)));
row_number = idx1(idx2);
row_number = row_number(1) %e.g.

Catégories

En savoir plus sur Shifting and Sorting Matrices 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