필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
Rachel Ong
Rachel Ong 2022년 3월 20일
편집: Torsten 2022년 3월 20일
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에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by