Array indices must be positive integers or logical values.

3 vues (au cours des 30 derniers jours)
Grégoire
Grégoire le 15 Fév 2024
Modifié(e) : Matt J le 15 Fév 2024
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 commentaires
DGM
DGM le 15 Fév 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 le 15 Fév 2024
yeah but they can be negative too, the roots are in between [-1;0] and [1;2]

Connectez-vous pour commenter.

Réponse acceptée

Matt J
Matt J le 15 Fév 2024
fx = @(X) X.^2-1-sin(X);
  3 commentaires
Matt J
Matt J le 15 Fév 2024
Modifié(e) : Matt J le 15 Fév 2024
Yes. In other words, it makes fx a function (or more precisely a function handle).
Grégoire
Grégoire le 15 Fév 2024
ok thanks :)

Connectez-vous pour commenter.

Plus de réponses (1)

VBBV
VBBV le 15 Fév 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.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by