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

조회 수: 16 (최근 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