# How to choose value from array based on closest value

9 Ansichten (letzte 30 Tage)
Alex am 13 Jul. 2022
Beantwortet: Ruchika P Barman am 13 Jul. 2022
I have a 41x2 array. I want to take an input variable, find the closest value in the first column, and assign the corresponding value in the second column to a new variable.
Any pointers on how I would go about doing this?
For example:
1. Input value is x = 3.2
2. Search first column in array for 3.2
3. Closest value is 3
4. Value in 2nd column corresponding to 3 is 500
5. Store 500 to new variable y
Thanks!
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Walter Roberson am 13 Jul. 2022
If the values in the first column are sorted, use interp1() with 'nearest'
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Alex am 13 Jul. 2022
This worked perfectly, thanks!

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Ruchika P Barman am 13 Jul. 2022
It is my understanding that you are trying to get the element closest to the input number by comparing with all the elements in the matrix column-wise. The following code should be able to achieve the same.
V=[0.87]
V = 0.8700
arr = rand(41,2)
arr = 41×2
0.0928 0.4712 0.5737 0.6716 0.0275 0.0357 0.3457 0.5579 0.6198 0.3686 0.1062 0.9167 0.5590 0.4408 0.1859 0.6384 0.8755 0.7567 0.3914 0.0726
for c=1:2
N=arr(:,c);
A = repmat(N,[1 length(V)]);
[minValue,closestIndex] = min(abs(A-V'));
closestValue = N(closestIndex);
V=closestValue;
end
V
V = 0.8895
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!

Translated by