Clear Filters
Clear Filters

Index of the row

1 view (last 30 days)
Imner Renmi
Imner Renmi on 8 Jul 2016
Commented: Star Strider on 8 Jul 2016
Hi,
I have a 5000 by 1 vector and I have a scalar, which is NOT part of the vector. I want to find the row number of the closest value to the scalar in the vector. The vector contains both positive and negative numbers and the scalar can be positive and negative too.
Anyone an idea of how to code this in Matlab.
Many thanks

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 8 Jul 2016
Edited: Azzi Abdelmalek on 8 Jul 2016
[~,idx]=min(abs(your_vector-threshold))
  1 Comment
Imner Renmi
Imner Renmi on 8 Jul 2016
Just to be sure, it will also work well for the negative values right?

Sign in to comment.


Star Strider
Star Strider on 8 Jul 2016
This workd:
vector = randi([-99,99], 100, 1); % Create Data
scalar = 100*(rand-0.5); % Create Data
[vs,idx] = sort(vector); % Sort
q = find(vs <= scalar, 1, 'last'); % Find Lowest Close Value
[q2,ixm] = min(vs([q, q+1])); % Mininmum Distance
nearest = vs(q+ixm-1) % Result
  2 Comments
Imner Renmi
Imner Renmi on 8 Jul 2016
What are 'vs' and 'idx'?
Star Strider
Star Strider on 8 Jul 2016
The ‘vs’ array is the sorted ‘vector’. The ‘idx’ vector are the original indices of the elements of the sorted vector. If you want the index instead of the value for ‘nearest’, that assignment becomes:
nearest_idx = idx(q+ixm-1)

Sign in to comment.

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!