find nearest value on matrix

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 件)

Roger Stafford
Roger Stafford 2016 年 5 月 9 日

1 投票

result = min(b(b>=1250));
For this to work, there has to be at least one element of b that is greater than or equal to 1250.

1 件のコメント

Image Analyst
Image Analyst 2016 年 5 月 9 日
Or, using the poster's names for variables:
closestValue = min(matrix_b(matrix_b >= a));

サインインしてコメントする。

Walter Roberson
Walter Roberson 2016 年 5 月 9 日
編集済み: Walter Roberson 2020 年 8 月 11 日

0 投票

v = sort(matrix_b(:));
vidx = floor(interp1(v, 1:length(v), a, 'linear', 'extrap'));
if vidx ~= 0
result = v(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.)

4 件のコメント

Walter Roberson
Walter Roberson 2016 年 5 月 9 日
If you have R2016a or later, then
v = sort(matrix_b(:));
result = interp1(v, v, a, 'previous');
FSh
FSh 2020 年 8 月 11 日
none of them works
Walter Roberson
Walter Roberson 2020 年 8 月 11 日
The first of them did have a mistake, which I have now corrected.
Could you give an example that fails for the others?
Walter Roberson
Walter Roberson 2020 年 8 月 11 日
Another approach:
v(interp1(v,1:length(v), a, 'nearest', 'extrap'))

サインインしてコメントする。

カテゴリ

質問済み:

2016 年 5 月 9 日

コメント済み:

2020 年 8 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by