How to get an average of two cells in specific conditions?

2 visualizzazioni (ultimi 30 giorni)
Hello,
I'm working with a rather large Excel document that I'm importing into Matlab 2016b (or 2019b as well) and trying to manipulate, the data is degrees of a circle as an array of 960x13.
For example:
x = [ 23.50128 22.0385 18.058
35.71267 25.44106 13.09361
9.335854 218.1108 -0.63557
40.69297 27.41063 -1.69481
27.22272 25.38112 -0.57529 ]
I need to average any number within the array that is greater than 90, or less than -90, with the number above and below it then replace the value that exceeds those parameters. In this example, I need 218.1108 to be instead be replaced with the averave of 25.44106 and 27.41063, the rest being left alone. I'm sure I'll have to use some sort of If statement to specify it but I'm uncertain on how to really get at this. Additionally, I run into the problem that sometimes the number outside of the parameters will be directly followed by another number outside the parameters and should in this case not be averaged with it but with the two numbers directly proceeding or following it. This may be rather complicated, but if anyone has any advice on how to approach this it would be greatly appreciated!
Thank you!

Risposta accettata

Marco Riani
Marco Riani il 2 Gen 2020
Hi GDT, please let me know if the code below solves your problem.
x = [ 23.50128 22.0385 18.058
35.71267 25.44106 13.09361
100 218.1108 91
110 27.41063 92
27.22272 25.38112 -0.57529 ];
y=x;
% Find the position of the values which have to be replaced
ind2replace=find(abs(x)>90);
% loop over ind2replace
for i=1:length(ind2replace)
indi=ind2replace(i);
% Find position of first element smaller than 90 before indi
posbefore=find(abs(x(1:indi))<90,1,'last');
% Find position of first element smaller than 90 after indi
posafter=indi+find(abs(x(indi:end))<90,1,'first')-1;
% Take the average of x(posbefore) and x(posafter)
y(indi)=0.5*(x(posbefore)+x(posafter));
end
disp('Before')
disp(x)
disp('After')
disp(y)
Before (x)
23.5013 22.0385 18.0580
35.7127 25.4411 13.0936
100.0000 218.1108 91.0000
110.0000 27.4106 92.0000
27.2227 25.3811 -0.5753
After (y)
23.5013 22.0385 18.0580
35.7127 25.4411 13.0936
31.4677 26.4258 6.2592
31.4677 27.4106 6.2592
27.2227 25.3811 -0.5753
Of course an additional if has to be put if the element to replace is the first or the final one.
Happy new year!

Più risposte (1)

David Hill
David Hill il 2 Gen 2020
You could try something like:
a=find(x>90|x<-90);
for i=1:length(a)
x(a(i))=mean(x([a(i)-1,a(i)+1]));
end

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by