MATLAB: Selecting an element of a vector

vector element

How to select an element of a vector which is nearest to the given value xp.
Suppose we have a vector
x=[1 1.05 1.1 1.15 1.2 1.25]
a) if xp=1.18, the output should be 1.2 (which is nearest to 1.18)
b) if xp=1.12, the output should be 1.1 (which is nearest to 1.12)

Best Answer

x=[1 1.05 1.1 1.15 1.2 1.25];
xp=input('Enter the xp value: ');
[d, idx]=min(abs(x-xp));
fprintf('The output is%.2f',x(idx));
Command Window
Enter the xp value: 1.18
The output is1.20