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

2 次查看(过去 30 天)
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.

回答(2 个)

Star Strider
Star Strider 2022-3-20
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 2022-3-20
编辑:Torsten 2022-3-20
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.

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by