Calculating Harmonic Average in Matlab Function

Hello,
I'm trying to calculate harmonic average in a Matlab function.
When I wrote the code below, I noticed Matlab doesn't seem to understand (i) as a counter variable.
Please advise why is this and how to resolve it. Thanking you in advance.
In main code I have:
kx = [10,20,30];
ky = [70,80,90];
In a function, I have:
function [harmonic_average] = harmonic_perm(kx,ky)
kxharmforward(i) = 2*(kx(i)*kx(i+1))/(kx(i)+kx(i+1)); % harmonic average for 20 & 30
kxharmbackward(i) = 2*(kx(i)*kx(i-1))/(kx(i)+kx(i-1)); % harmonic average for 10 & 20
kyharmupward(i) = 2*(ky(i)*ky(i+1))/(ky(i)+ky(i+1)); % harmonic average for 80 & 90
kyharmdownward(i) = 2*(ky(i)*ky(i-1))/(ky(i)+ky(i-1)); % harmonic average for 70 & 80
end
This is the error I get when I run the code
Array indices must be positive integers or logical values.
Error in harmonic_perm (line 3)
harmonic_average(i) = 2*(kx(i)*kx(i+1))/(kx(i)+kx(i+1));
Error in Main_Code (line 139)
harnomic_average(i)=harmonic_perm(kx(i),ky(i))

Answers (1)

What is ky? Why not just perform vectorized? No need to index into k. k can be any length vector and the below will calculate the harmonic mean.
function harmonic_average = harmonic_perm(k)
harmonic_average = numel(k)/sum(1./k);
end

5 Comments

Hi David, thanks for your answer.
ky was a typo as I was trying to calculate harmonic average in both x and y direction. I've edited the post and removed it from the code.
I'm trying to understand why Matlab doesn't recognize the (i) as a placeholder because I have to use functions containing it in my code.
I'm using harmonic average as a simple example to explain my problem.
When you index into an array, the i must be a positive integer value. You never specify the value of i. Look at matlab help, array indexing.
function harmonic_average = harmonic_perm(x,y)
harmonic_average = [numel(x)/sum(1./x),numel(y)/sum(1./y)];
end
%after computing, harmonic_average(1)=harmonic mean of x and harmonic_average(2)=harmonic mean of y
Thanks David.
I do understand your logic and code, but maybe I'm not explaining myself correctly.
I'll edit the post to make my question clearer as I'm trying to use i as a counter variable.
Please see post above again. I'm trying to write average permeability code in terms of kx(i), kx(i+1), kx(i-1) and ky(i), ky(i+1), ky(i-1)
function harmonic_average = harmonic_perm(kx,ky)
harmonic_average=zeros(1,4);
for i=1:2
harmonic_average(i) = 2/sum(1./kx(i:i+1));
harmonic_average(i+2)= 2/sum(1./ky(i:i+1));
end
end

Sign in to comment.

Asked:

on 12 Jul 2020

Commented:

on 13 Jul 2020

Community Treasure Hunt

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

Start Hunting!