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 个)

Community Treasure Hunt

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

Start Hunting!

Translated by