Array indices must be positive integers or logical values.

3 次查看(过去 30 天)
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 个评论
DGM
DGM 2024-2-15
a and b are not constrained to being positive nonzero integers, so you can't use them as array indices.
Grégoire
Grégoire 2024-2-15
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 个评论
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).

请先登录,再进行评论。

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by