Asked by Karlie Brillant
on 23 Apr 2019 at 14:41

Working on a scipt to run a function for flow of water through a pipe

Script:

dh=1.0;

for R_e=linspace(1*10^3,1*10^5,10)

k=linspace(1*10^-6,1*10^-3,10);

f=pipe(R_e,k);

end

for k=linspace(1*10^-6,1*10^-3,10)

R_e=linspace(1*10^3,1*10^5,10);

f=pipe(R_e,k);

end

x=R_e;

y=k;

[x,y]=size(z);

surface(x,y,z);

Function:

function f=pipe(R_e,k)

i=1;

f=64/R_e(i);

if R_e<=2000

f(i)=64/R_e(i);

disp('Laminar flow');

end

if R_e>2000

f(i)=(2*log10((2.51/R_e(i)*(f)^0.5)+((k(i)/dh)/3.72))).^-2;

disp('Turbulent flow');

end

f(i+1)=(2*log10((2.51/R_e(i+1)*(f(i)^0.5)+((k(i+1)/dh)/3.72))).^-2)

change_in_f=f(i+1)-f(i);

i=4;

while change_in_f>1*10^-5

f(i)=(2*log10((2.51/R_e(i)*(f(i-1)^0.5)+((k(i)/dh)/3.72)))).^-2;

change_in_f=guess_f(i-1)-guess_f(i);

i=i+1;

end

end

It is getting stuck on line 14

f(i+1)=(2*log10((2.51/R_e(i+1)*(f(i)^0.5)+((k(i+1)/dh)/3.72))).^-2)

It says the index exceeds the number of array elements, but I cannot figure out why. Each of my vectors appears to call a specific element, so why am i getting this error?

Answer by Stephen Cobeldick
on 23 Apr 2019 at 14:52

Edited by Stephen Cobeldick
on 23 Apr 2019 at 15:03

On each loop iteration the loop iterator variable R_e is scalar (i.e. it has size 1x1). Inside the function you define i=1 and then try to access R_e(i+1), i.e. you are trying to access the second element of an array which only contains one element. This is an error.

I do not know how to fix this because you code does not make much sense to me: in partcular those for loops are vey confusing: you should probably be looping over indices, rather than over values. Looping over indices would also resolve the next question you would ask on this forum, about why the loop only stores the last value that you calculate and discards the rest (hint. you need to use indexing on the output array too).

How to use a loop (with indexing to store the output values) is shown in the introductory tutorials, which are highly recommended for learning basic MATLAB concepts:

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.