hi..lets say there i a vector x=[1:3:50]..how can i find closest number to 25 in this vector using find??

hi..lets say there is a vector x=[1:3:50]..how can i find closest number to 25 in this vector using find??

 Accepted Answer

>> val = 26;
>> vec = 1:3:50;
>> [~,idx] = min(abs(vec-val));
>> vec(idx)
ans = 25

3 Comments

>> val = 26;
>> vec = 1:3:50;
>> d = abs(x-val);
>> idx = find(min(d)==d)
idx = 9
>> vec(idx)
ans = 25
I don't see the point though. Pointlessly complicated.
There is the possibility that the question writer meant to ask to find the vector element equal to the scalar value, in which case this is trivial:
>> val = 25;
>> idx = find(val==vec);
>> vec(idx)
ans = 25
However I still would not recommend using find for this purpose, as logical indexing is simpler and faster:
>> idy = vec==val;
>> vec(idy)
ans = 25

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB 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!