Optimization of manipulating an array

2 ビュー (過去 30 日間)
Mahmood AL Imam
Mahmood AL Imam 2022 年 2 月 28 日
コメント済み: Mahmood AL Imam 2022 年 3 月 1 日
I have an array, where 0s are between non-zeros integer or floating numbers.
>> a = [1, 0, 5, 0, 6, 0, 12, 0];
I am looking to find the average of every adjacent two numbers and insert it to replace the zero between them:
like for the example above:
>> b = [1, 3, 5, 5.5, 6, 9, 12, 15]
For the last 0, we should add the difference between 12 and 9 to the last value, which is 12. So that makes (12 - 9) + 12.
I am looking for an optimized code (may be if possible without loop).
Thanks

採用された回答

Ive J
Ive J 2022 年 2 月 28 日
a = [1, 0, 5, 0, 6, 0, 12, 0];
b = a;
a_adj_mean = movmean(a(1:2:end), 2);
zero_idx = a == 0;
b(zero_idx(1:end - 1)) = a_adj_mean(2: end);
b(end) = 2*b(end-1) - b(end - 2)
b = 1×8
1.0000 3.0000 5.0000 5.5000 6.0000 9.0000 12.0000 15.0000
  1 件のコメント
Mahmood AL Imam
Mahmood AL Imam 2022 年 3 月 1 日
Thank you very much Ive J

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2013a

Community Treasure Hunt

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

Start Hunting!

Translated by