why I am getting 'array indices must be positive intergers or logical value' error?

a=1.4492;
b=-3.4497;
n=100;
h=(b-a)/n;
f(a)=integ_trape(a);
f(b)=integ_trape(b);
r=0.5*(f(a)+f(b));
for i=1:1:n-1
r=r+f(a+i*h);
break;
I=h*r;
end

 채택된 답변

Some of the posted code makes no sense, especially the break call in the for loop, since that will result in only the first value of ‘r’ being calculated, and nothing else.
See if this is closer to what you want:
a=1.4492;
b=-3.4497;
n=100;
h=(b-a)/n;
f = @(q) integ_trape(q);
r=0.5*(f(a)+f(b));
for i=1:1:n-1
r = r+f(a+i*h);
% break;
I(i) = h*r;
end
I
I = 1×99
-0.0117 -0.0348 -0.0691 -0.1143 -0.1702 -0.2366 -0.3132 -0.3998 -0.4961 -0.6020 -0.7172 -0.8414 -0.9744 -1.1160 -1.2660 -1.4240 -1.5900 -1.7635 -1.9445 -2.1327 -2.3278 -2.5296 -2.7378 -2.9523 -3.1728 -3.3990 -3.6308 -3.8679 -4.1100 -4.3569
function fun3=integ_trape(x)
fun3=-x^2-2*x+5;
end
The ‘f’ anonymous function is also not necessary (it just calls ‘integ_trape’) however I kept it in for convenience.
.

댓글 수: 2

thank you!I am beginner in MATLAB,stil can't understand why
f(a)=integ_trape(a);
did'nt work as I called function in bisection method and it did work.
a=1;
b=2;
n=100;
tol=0.0001;
fa=func_rootfind_1(a);
fb=func_rootfind_1(b);
if(fa.*fb < 0)
for i=1:1:n;
c=(a+b)./2;
fa=func_rootfind_1(a);
fb=func_rootfind_1(b);
fc=func_rootfind_1(c);
if(abs(fc) < tol || abs(a-b) < tol)
root=c;
%i=n+1;
break;
else
if(fa.*fc < 0)
b=c;
else
a=c;
end
%i=i+1;
end
end
else
root=100000;
end
root
function fun1=func_rootfind_1(x)
z=x^3-x-1;
fun1=z

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by