How do I find the nearest value to a number that is bigger than that number?
58 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Janna Hinchliff
il 29 Gen 2019
Risposto: achillakos
il 27 Ott 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 Commenti
Risposta accettata
Guillaume
il 29 Gen 2019
Modificato: Guillaume
il 29 Gen 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 Commenti
Più risposte (1)
achillakos
il 27 Ott 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 Commenti
Vedere anche
Categorie
Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!