How do I find the nearest value to a number that is bigger than that number?
66 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Janna Hinchliff
le 29 Jan 2019
Réponse apportée : achillakos
le 27 Oct 2022
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?
0 commentaires
Réponse acceptée
Guillaume
le 29 Jan 2019
Modifié(e) : Guillaume
le 29 Jan 2019
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);
0 commentaires
Plus de réponses (1)
achillakos
le 27 Oct 2022
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)
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)
0 commentaires
Voir également
Catégories
En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!