Array indices must be positive integers or logical values.

Hey, I m trying to do a bissecion method code.
But when trying to give a var fa the value of f(a) it gives me a :'Array indices must be positive integers or logical values.'
Could anyone explain me why please ?
clear;
tol = 10^(-6);
x1= -2:0.01:2;
fx = x1.^2-1-sin(x1);
a=input('Intervalo inferior: ');
b=input('Intervalo superior: ');
fa=fx(a);
Array indices must be positive integers or logical values.
fb=fx(b);
if sign(fa)==sign(fb)
disp('no tiene solucion')
return
end
while (b-a)/2 > tol
c = (a+b)/2;
fc= fx(c);
if sign(a)==sign(c)
a=c;
fa=fc;
else
b=c;
fb=fc;
end
end
c

댓글 수: 2

a and b are not constrained to being positive nonzero integers, so you can't use them as array indices.
yeah but they can be negative too, the roots are in between [-1;0] and [1;2]

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

 채택된 답변

Matt J
Matt J 2024년 2월 15일
fx = @(X) X.^2-1-sin(X);

댓글 수: 3

It works thanks a lot !
So the @(X) allows you to be able to give to X every variable you want right ?
Matt J
Matt J 2024년 2월 15일
편집: Matt J 2024년 2월 15일
Yes. In other words, it makes fx a function (or more precisely a function handle).
ok thanks :)

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

추가 답변 (1개)

Matlab arrays are indexed using whole integers, when you give a fractional or decimal values as input it throws such errors
clear;
tol = 10^(-6);
x1= -2:0.01:2;
fx = x1.^2-1-sin(x1)
fx = 1×401
3.9093 3.8735 3.8378 3.8023 3.7668 3.7315 3.6962 3.6611 3.6260 3.5911 3.5563 3.5216 3.4870 3.4525 3.4181 3.3838 3.3496 3.3155 3.2815 3.2476 3.2138 3.1802 3.1466 3.1131 3.0798 3.0465 3.0133 2.9803 2.9473 2.9144
a=2.7 %input('Intervalo inferior: ');
a = 2.7000
b=3.2 %input('Intervalo superior: ');
b = 3.2000
fa=fx(round(a)) % round the input values
fa = 3.8378
clear;
tol = 10^(-6);
x1= -2:0.01:2;
fx = x1.^2-1-sin(x1)
fx = 1×401
3.9093 3.8735 3.8378 3.8023 3.7668 3.7315 3.6962 3.6611 3.6260 3.5911 3.5563 3.5216 3.4870 3.4525 3.4181 3.3838 3.3496 3.3155 3.2815 3.2476 3.2138 3.1802 3.1466 3.1131 3.0798 3.0465 3.0133 2.9803 2.9473 2.9144
a=2.5; %input('Intervalo inferior: ');
b=3.2; %input('Intervalo superior: ');
fa=fx(a)
Array indices must be positive integers or logical values.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

릴리스

R2023b

태그

질문:

2024년 2월 15일

편집:

2024년 2월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by