Take mean value when elements inside array "clump up"

I have an Array,for example:
r1 = rand(1000,1)
sort(r1)
and have this sorted in ascending order. What Im trying to accomplish is: I want to take the mean value whenever the values inside the arrays clump up and are in between a specific threshold. Trying to explain this in an example:
a = [1; 10; 15; 16; 16.1; 16.2; 16.3; 18]
Mean Value should always be taken when the number inside the array have a maximum difference of 0.5.
So here essentially this should be taken:
a_sub = [16; 16.1; 16.2; 16.3]
mean(a_sub)
I hope this is understandable. Any help is greatly appreciated.

4 件のコメント

the cyclist
the cyclist 2020 年 7 月 27 日
So, in this case, you want the output to be
out = [1; 10; 15; 16.15; 18];
?
Ko Fa
Ko Fa 2020 年 7 月 27 日
Im actually only interested in the mean value, the array is non of my concern anymore.
the cyclist
the cyclist 2020 年 7 月 27 日
Could there be more than one cluster in the same array? For example, could the input be something like
a = [0.1 0.2 0.3 5 6 7 0.8 0.9 1.0];
?
Ko Fa
Ko Fa 2020 年 7 月 27 日
yes

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

 採用された回答

the cyclist
the cyclist 2020 年 7 月 27 日
編集済み: the cyclist 2020 年 7 月 27 日

0 投票

Assuming that my guess about the correct output is correct, then the following should work.
% Original (sorted) data
a = [1; 10; 15; 16; 16.1; 16.2; 16.3; 18];
% The difference threshold
d = 0.5;
% Identify which "cluster" each value belongs to. This part is slightly tricky.
% The diff command will result in a value of 1 if the prior value is more than the threshold.
% By taking the cumulative sum, the index will therefore move to the next value.
clusterIndex = cumsum(diff([a(1); a]) > d) + 1;
% According to the index, take the mean over values that belong to the same cluster
out = accumarray(clusterIndex,a,[],@mean);

3 件のコメント

Ko Fa
Ko Fa 2020 年 7 月 27 日
Thanks a lot for your anwer!
Is there a way to then extract all the mean values calculated?
the cyclist
the cyclist 2020 年 7 月 28 日
a = [1; 2.1; 2.2; 10; 15; 16; 16.1; 16.2; 16.3; 18];
d = 0.5;
clusterIndex = cumsum(diff([a(1); a]) > d) + 1;
numberInCluster = histcounts(clusterIndex);
clusterMeans = accumarray(clusterIndex,a,[],@mean);
clusterMeansWithMoreThanOneValue = clusterMeans(numberInCluster>1);
Ko Fa
Ko Fa 2020 年 7 月 28 日
Thank you kind sir! I

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

質問済み:

2020 年 7 月 27 日

コメント済み:

2020 年 7 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by