Index of the row

1 次查看(过去 30 天)
Imner Renmi
Imner Renmi 2016-7-8
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

回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2016-7-8
编辑:Azzi Abdelmalek 2016-7-8
[~,idx]=min(abs(your_vector-threshold))
  1 个评论
Imner Renmi
Imner Renmi 2016-7-8
Just to be sure, it will also work well for the negative values right?

请先登录,再进行评论。


Star Strider
Star Strider 2016-7-8
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 个评论
Imner Renmi
Imner Renmi 2016-7-8
What are 'vs' and 'idx'?
Star Strider
Star Strider 2016-7-8
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)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by