フィルターのクリア

Calculates the mean if the difference of two or more number is 1

3 ビュー (過去 30 日間)
edward kabanyas
edward kabanyas 2021 年 2 月 7 日
コメント済み: edward kabanyas 2021 年 2 月 9 日
Hi all;
I want to calculate mean of numbers if their difference with its neighbor is 1 . For example, if I have a matrix:
A = [9 10 12 14 15 16 18 19 22 23 25];
For each number whose difference with the neighbors is one, their mean is calculated. So, the intended result (called as matrix B):
B [9.5 12 15 18.5 22.5 25];
I try to use:
diff(A), so we get
1 2 2 1 1 2 1 3 1 2
But, how to use this diff(A) to do an operation , so that we get the resul: B [9.5 12 15 18.5 22.5 25];
Thank you for help.

採用された回答

Matt Gaidica
Matt Gaidica 2021 年 2 月 8 日
編集済み: Matt Gaidica 2021 年 2 月 8 日
A = [9 10 12 14 15 16 18 19 22 23 25];
idx = find(diff(A)==1);
B = mean([A(idx);A(idx+1)])
I think you have a typo above, 25 would not be in the final array:
B =
9.5000 14.5000 15.5000 18.5000 22.5000
Could also:
mv = movmean(A,2);
idx = find(diff(A)==1);
B = mv(idx+1)
  6 件のコメント
Matt Gaidica
Matt Gaidica 2021 年 2 月 8 日
Not my proudest code snippet, but at least you can step through it and see what's going on:
A = [9 10 12 14 15 16 18 19 22 23 25];
B = [];
arr = [];
ii = 1;
while ii <= numel(A)
arr(1) = A(ii);
while ii~= numel(A) && A(ii+1) == A(ii)+1
arr = [arr A(ii+1)];
ii = ii + 1;
if ii > numel(A) - 1
break;
end
end
B = [B mean(arr)];
ii = ii + 1;
arr = [];
end
B
edward kabanyas
edward kabanyas 2021 年 2 月 9 日
great Matt

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by