How to compute harmonic average on the blocks of an array?

Hi,
I have attached the data Mmin, I want to compute the harmonic average of first 4 values and then next 4 and so on. In short in the blocky form and each block is of 4 values.
Just like shown in the attached figure. after taking harmonic mean of first four values, there will be one value instead of four and so on.
Can someone help me to write it code?
Thanks

 Accepted Answer

a=randi(100,1,100);%some vector
for k=1:length(a)-3
A(k)=harmmean(a(k:k+3));
end

4 Comments

Altneratively, simpler.
a=randi(100,1,100);
A=4./movsum(1./a,4,'Endpoints','discard');
@David Hill Can you explain a littele bit,
Actually when I did it on my data, say if length of a = 1612 and after haromic mean it reduces to 1609. why?
while if it is performing harmonic mean of say first four values and then next four values and then next four values and so no, the length of a should decrease 4 times as 1612/4 = 403?
Can you please explain how it is working?
I misunderstood you. I thought you wanted a rolling harmonic mean 1-4 then 2-5, then 3-6, 4-7, etc. I simple change will correct.
a=randi(100,1,32);%some vector
c=1;
for k=1:4:length(a)-3
A(c)=harmmean(a(k:k+3));
c=c+1;
end
A
A = 1×8
7.1646 42.5475 57.0370 11.6593 49.3414 59.0867 62.9062 33.5323
Or
m=movsum(1./a,4,'Endpoints','discard');
A=4./m(1:4:end)
A = 1×8
7.1646 42.5475 57.0370 11.6593 49.3414 59.0867 62.9062 33.5323
@David Hill thanks, One more thing is if I want to compute moving harmonic mean (like 1-4 then 2-5, then 3-6, 4-7, etc. ) as you did in your previous comment and want to keep the length of array same as before applying moving harmonic mean. How I can do it? e.g.
a=randi(100,1,100);%some vector
for k=1:length(a)-3
A(k)=harmmean(a(k:k+3));
end
length(A) should be equal to length(A)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!