Assign nearest maximum value.

9 ビュー (過去 30 日間)
MakM
MakM 2022 年 2 月 9 日
回答済み: Image Analyst 2022 年 2 月 9 日
I have a vector named A=[10,20,30,40], Suppose I need to find the number 25 from that vector, as 25 is not present in this vector, it should give me 30, i.e, nearest maximum value. How can I do that?

採用された回答

Walter Roberson
Walter Roberson 2022 年 2 月 9 日
A=[10,20,30,40]
A = 1×4
10 20 30 40
q = 25
q = 25
A(find(A >= q, 1))
ans = 30
However, your meaning of "nearest" is not completely clear. If the query had been for 24 instead of 25, then should 20 be output, since (24-20) < (30-24) ? And what does "nearest" mean if A is not in sorted order? Closest position in either direction that has a value at least as great? Position that has the least positive difference in value? And what should be done if the query value is out of range for A ?
  2 件のコメント
MakM
MakM 2022 年 2 月 9 日
By nearest I mean, the value greater than the 25, because the vector is sorted. And if the query value is out of range it should select the value that is less. For example for this example, for 45 it should give 40.
Walter Roberson
Walter Roberson 2022 年 2 月 9 日
idx = find(A >= q, 1);
if isempty(idx); idx = numel(A); end
nearest = A(idx)

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

その他の回答 (2 件)

Jan
Jan 2022 年 2 月 9 日
Why 30 and not 20? Both have a distance of 5.
A = [10,20,30,40];
S = 25;
[~, index] = min(abs(A - S));
A(index)
ans = 20
  1 件のコメント
MakM
MakM 2022 年 2 月 9 日
I need to get the maximum value because the vector is sorted, so for 25 it should give 30 but if the value comes which is out of range then , for example in that case, if 45 comes it should give 40.

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


Image Analyst
Image Analyst 2022 年 2 月 9 日
Try this:
% Set up sample values.
A = [10, 20, 30, 40];
searchValue = 25;
% Get the distance from the array to the search value.
diffs = abs(A - searchValue)
% Find the min distance.
minDistanceValue = min(diffs)
% Find all indexes where the min difference occurs.
locations = find(diffs == minDistanceValue) % Returns [2, 3] since those locations are both 5 away from 25.
% If multiple locations, get the max of the values that meet the criteria.
maxValue = max(A(locations)) % Returns 30

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by