Array indices must be positive integers or logical values.

1 view (last 30 days)
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 Comments
DGM
DGM on 15 Feb 2024
a and b are not constrained to being positive nonzero integers, so you can't use them as array indices.
Grégoire
Grégoire on 15 Feb 2024
yeah but they can be negative too, the roots are in between [-1;0] and [1;2]

Sign in to comment.

Accepted Answer

Matt J
Matt J on 15 Feb 2024
fx = @(X) X.^2-1-sin(X);
  3 Comments
Matt J
Matt J on 15 Feb 2024
Edited: Matt J on 15 Feb 2024
Yes. In other words, it makes fx a function (or more precisely a function handle).

Sign in to comment.

More Answers (1)

VBBV
VBBV on 15 Feb 2024
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.

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!