How do i get index of a closest value from an array?

3 ビュー (過去 30 日間)
yashvin
yashvin 2015 年 7 月 10 日
編集済み: Thorsten 2015 年 7 月 18 日
Hello ,
My array is
a=[0 200 900 1000 1200 1798 1799 1801 2000 2700 3601]
I want to find all the index of numbers which are multiples of 900. In case the multiples are not present in the array, find the index of the closest number matching the multiples.
I want to find for multiples of 900
I tried this
Index= mod(a,900) == 0
index_chunk=find(Index == 1)
but it does not give me index of the closest number of multiples of 900.

回答 (2 件)

Jan Orwat
Jan Orwat 2015 年 7 月 10 日
Try something like this:
divisor = 900;
how_close_is = abs(mod(a+divisor/2,divisor)-divisor/2);
index_chunk=find(how_close == min(how_close));
or add a parameter:
closer_than = 10; % adjust to your needs
index = abs(mod(a+divisor/2,divisor)-divisor/2) <= closer_than;
index_chunk = find(index);
  1 件のコメント
yashvin
yashvin 2015 年 7 月 13 日
編集済み: yashvin 2015 年 7 月 13 日
@ Jan, if i change the closer_than=0, it picks
1 3 7 8 10 11
7 and 8 corresponds to 1799 and 1801. In fact, i want the index of any of the numbers- not both..Which approach would you suggest?

サインインしてコメントする。


Thorsten
Thorsten 2015 年 7 月 10 日
編集済み: Thorsten 2015 年 7 月 10 日
N = round(max(a)/900);
for i = 1:N, [~, ind(i)] = min(abs(a - 900*i)); end
  3 件のコメント
yashvin
yashvin 2015 年 7 月 13 日
I have many streams of a. For each stream, how can i store its corresponding ind. If I try to make ind a cell, it says error.
Thorsten
Thorsten 2015 年 7 月 18 日
編集済み: Thorsten 2015 年 7 月 18 日
To include 0, use
for i = 0:N, [~, ind(i+1)] = min(abs(a - 900*i)); end
To store the indices in a cell C, when all the a's a stored in cell A:
for j = numel(A) % loop through all a's
a = A{j};
for i = 0:N, [~, ind(i+1)] = min(abs(a - 900*i)); end
C{j} = ind;
end

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by