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

48 次查看(过去 30 天)
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 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