Replacing value by the mean of the two nearest neighbors

17 vues (au cours des 30 derniers jours)
Ludovica Maria Campagna
Ludovica Maria Campagna le 26 Sep 2022
Commenté : Alexis le 24 Jan 2024
I have a column vector:
B = [20; 18; NaN; 25; 100; 15; -50; 23]
B = 8×1
20 18 NaN 25 100 15 -50 23
I need to pre-process data, so I want to:
  1. replace numbers greater than a certain value (e.g. numbers greater than 40) with the average of the two adjacent numbers.
  2. replace numbers smaller than a certain value (e.g. numbers smaller than -10) with the average of the two adjacent numbers.
  3. replace missing value with the average of the two adjacent numbers.
Thank you!
  2 commentaires
Torsten
Torsten le 26 Sep 2022
The result will depend on the order in which you perform these operations.
So order doesn't matter ?
Ludovica Maria Campagna
Ludovica Maria Campagna le 27 Sep 2022
Yes, it doesn't matter!

Connectez-vous pour commenter.

Réponse acceptée

David Hill
David Hill le 26 Sep 2022
B = [20; 18; NaN; 25; 100; 15; -50; 23; NaN; 15; -15; 30];
idx=find(isnan(B));
B(idx)=mean([B(idx-1),B(idx+1)],2);
idx=find(B<-10);
B(idx)=mean([B(idx-1),B(idx+1)],2);
idx=find(B>40);
B(idx)=mean([B(idx-1),B(idx+1)],2)
B = 12×1
20.0000 18.0000 21.5000 25.0000 20.0000 15.0000 19.0000 23.0000 19.0000 15.0000
  1 commentaire
Alexis
Alexis le 24 Jan 2024
This won't work if two consecutive values appear

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by