Trying to find the error in my modified false position method code

조회 수: 5 (최근 30일)
Lily
Lily 2024년 4월 16일
답변: lavanya 2024년 9월 13일
I am getting this error (Index exceeds the number of array elements. Index must not exceed 1) for my code and unsure why. Any help would be appreciated.
clc;
clear all;
close all;
%Mini Project
%Modified False Position Method
syms f(x);
f(x)=(-4.868e-7)*(4*x^3)+(1.496e-4)*(3*x^2)+(-0.0094)*(2*x)+(-0.3324);
i=1;
xl(i)=150;
xu(i)=200;
iu(i)=0;
il(i)=0;
fu(i)=f(xu(i));
fl(i)=f(xl(i));
xr(i)=xu(i)-((fu(i)*(xl(i)-xu(i))/(fl(i)-fu(i))));
fr(i)=f(xr(i));
ea = zeros(1,i);
if f(xr(i))~=0
while i<100
i=i+1;
if fl(i-1)*fr(i-1)<0
xu(i)=xr(i-1);
xl(i)=xl(i-1);
iu(i)=iu(i-1);
il(i)=il(i-1)+1;
if il(i)>=2
fl(i)=fl(i-1)/2;
fu(i)=fr(i-1);
end
else
xl(i)=xr(i-1);
xu(i)=xu(i-1);
il(i)=il(i-1);
iu(i)=iu(i-1)+1;
if iu(i)>=2
fu(i)=fu(i-1)/2;
fl(i)=fr(i-1);
end
end
xr(i)=xu(i)-((fu(i)*(xl(i)-xu(i))/(fl(i)-fu(i))));
fr(i)=f(xr(i));
ea(i)=abs((xr(i)-xr(i-1))/xr(i))*100;
if ea(i)<0.05
break;
end
end
end
Index exceeds the number of array elements. Index must not exceed 1.

Error in indexing (line 962)
R_tilde = builtin('subsref',L_tilde,Idx);
figure(1)
plot(ea)
hold on
grid on
xlabel('Iteration')
ylabel('Percent Approximation Error')
y=-200:10:200;
figure(2)
hold on
grid on
box on
for i=1:1:length(y)
plot(y,f(y),'LineWidth',2)
end
plot(xr,f(xr),'*','MarkerSize',10);
xlabel('Temperature (K)')
ylabel('Derivative of f(T)')
yline(0);
xr=double(xr);
r_mfpm=(-4.868e-7)*(xr^4)+(1.496e-4)*(xr^3)+(-0.0094)*(xr^2)+(-0.3324*xr)+14.55;
et=abs((166.222229010761-xr)/-166.222229010761)*100;
  댓글 수: 1
James Tursa
James Tursa 2024년 4월 16일
To debug this, type the following at the command prompt:
dbstop if error
Then run your code. When the error occurs, the program will pause at the line causing the error with all variables intact. Then you can examine the variables on that line to figure out the cause of the error. In your case, some of the variables are scalars but you are using an index of 2, hence the error. Backtrack in your code to figure out why these variables are not the size you expected.

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

답변 (2개)

Aman
Aman 2024년 4월 22일
Hi Lily,
You are getting the below error from the below line:
xr(i)=xu(i)-((fu(i)*(xl(i)-xu(i))/(fl(i)-fu(i))));
Here "fl" and "fu" are 1x1 syms, and the code is trying to access the second index, due to which it is erroring out. Please reiterate your code once and make appropriate changes, like accessing the proper index or assigning the proper type to the "fl" and "fu.".
I hope this helps!

lavanya
lavanya 2024년 9월 13일
Find the volume of the solid generated by revolving about the x -axis the region bounded by the curve y = √x , the x−axis, and the line y = x − 2 in matlab with a graph

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by