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.
0 个评论
回答(2 个)
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,:)
[~,idx] = min(Out(:,2));
Result = Out(idx,:)
.
0 个评论
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!