Clear Filters
Clear Filters

From a given number how to find the value closest to zero in a vector.

36 views (last 30 days)
If a have a vector [93.60 119.15 136.19 191.55 238.39 268.20 302.27 340.60 383.18 425.77] and a number that every time is different.For example numb=410 i want to find the number 383.18 from the vector.

Accepted Answer

Star Strider
Star Strider on 27 Sep 2016
Use the find function:
vector = [93.60 119.15 136.19 191.55 238.39 268.20 302.27 340.60 383.18 425.77];
numb=410;
idx = find(vector <= numb, 1, 'last');
Result = vector(idx)
Result =
383.18

More Answers (1)

Kelly Kearney
Kelly Kearney on 27 Sep 2016
Star's answer works in the values in the vector are sorted. If not, min might be a better choice:
vector = [93.60 119.15 136.19 191.55 238.39 268.20 302.27 340.60 383.18 425.77];
numb=410;
[~, imin] = min(abs(vector - num));
vector(imin)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!