Index exceeds number of array elements?

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?

답변 (1개)

Stephen23
Stephen23 2019년 4월 23일
편집: Stephen23 2019년 4월 23일

0 개 추천

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:

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2019년 4월 23일

편집:

2019년 4월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by