How do I find the nearest value to a number that is bigger than that number?

109 ビュー (過去 30 日間)
Janna Hinchliff
Janna Hinchliff 2019 年 1 月 29 日
回答済み: achillakos 2022 年 10 月 27 日
I'm using the command
[~,indexToClosestMatch] = min(arrayfun(@(x)min(abs(x-val)),matrixcellarray{j}(:,1)));
to find the value in matrixcellarray{j}(:,1) that is closest in value to the number val. I want to additionally specify that I only want to consider values in matrixcellarray{j}(:,1) that are higher than val - i.e. if matrixcellarray{j}(:,1) was [1 2 5 6] and val was 3, I would want it to match to 5, not 2, as although 2 is closer, it is lower than 3. How can I achieve this?

採用された回答

Guillaume
Guillaume 2019 年 1 月 29 日
編集済み: Guillaume 2019 年 1 月 29 日
First, your command is overly complicated. arrayfun always pass scalar values to its function, so the x is your anonymous function is always be to be scalar (in turn each element of matrixcellarray{j}(:,1)). So abs(x-val) is scalar, and the minimum of a scalar value is always that value. The arrayfun is completely unnecessary, your code is the same as:
[~, indexToClosestMatch] = min(abs(matrixcellarray{j}(:,1) - val));
There are many ways you could achieve what you want. One way:
distancefromval = matrixcellarray{j}(:,1) - val;
distancefromval(distancefromval < 0) = +Inf;
[~, indexToClosestMatch] = min(distancefromval);
Another way:
greaterindices = find(matrixcellarray{j}(:,1) > val);
[~, intermediateindex] = min(matrixcellarray{j}(greaterindices, 1) - val));
indexToClosestMatch = greaterindices(intermediateindex);

その他の回答 (1 件)

achillakos
achillakos 2022 年 10 月 27 日
An easy way to quickly find the closest, either higher or lower, entries of an array to a specific value is to use the interp1 function with the 'next' option.
In the case that you have an array arr = [1 2 5 6] and the value is val = 3, and you want the closest higher entry, that would be:
arr = [1 2 5 6];
val = 3;
[~,indexToClosestMatch] = find(arr==interp1(arr,arr,val,'next'),1)
indexToClosestMatch = 3
In your case you just need to substitue arr for matrixcellarray{j}(:,1), and that would look like:
[~,indexToClosestMatch] = find(matrixcellarray{j}(:,1)==interp1(matrixcellarray{j}(:,1),matrixcellarray{j}(:,1),val,'next'),1)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by