필터 지우기
필터 지우기

'Index exceeds matrix dimensions' error

조회 수: 1 (최근 30일)
Soho
Soho 2017년 7월 12일
댓글: Moe_2015 2017년 7월 12일
Hi, I'm trying to write an iteration program that runs a while loop until the variable 'theta' is almost the same as the output x (within a certain accuracy). I keep getting this error, but when I try to change the code to run, it only runs for the first loop. Can anyone help? My code is below (i've been using 0.01 as thetaInitial because i know this is pretty close to the correct answer)
function x=iteration(thetaInitial)
theta(1)=thetaInitial;
x(1)=0.0248;
error=1e-8;
Re=10000;
i=1;
while abs(x(i)-theta(i))>error
x(i)=(((6.25*log(2))+1.5)*log(Re*(theta(i)^0.5))+0.09)^-1;
i=i+1;
end
x=x(1:i+1);
plot(x)
[x(end) i]

채택된 답변

Moe_2015
Moe_2015 2017년 7월 12일
theta(i) is not defined after the first index. You set theta(1) but then never do anything with theta again. So when you say theta(i) it is exceeding the matrix dimension (which is 1). Also, you should move i = i+1 as the first line inside the while loop. Also outside the while loop x =x(1:i+1) will fail because you do not reach an x with length (i+1)... your x will be of length i
  댓글 수: 1
Moe_2015
Moe_2015 2017년 7월 12일
So something like this (note: set theta(i) to whatever it should be):
function x=iteration(thetaInitial)
theta(1)=thetaInitial;
x(1)=0.0248;
error=1e-8;
Re=10000;
i=1;
while abs(x(i)-theta(i))>error
i=i+1;
theta(i) = 0; %set this to whatever it is supposed to be
x(i)=(((6.25*log(2))+1.5)*log(Re*(theta(i)^0.5))+0.09)^-1;
end
x=x(1:i); % this line isn't really necessary but if you want it this is what it should be
plot(x)
[x(end) i]

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by