Why am I getting Error "Array indices must be positive integers or logical values"?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
N=[5 6 7 8 9 10 11 12 13 14 15];
fprintf('%5s\t%15s\t%15s\t%15s\n','n','T(h)','En','En/E(n-1)')
trueValue = exp(-2.5).*(-sin((2.5).^3)-sin((2.5).^2)+2.*(2.5).*cos((2.5).^3)+3.*(2.5).^2.*cos((2.5).^3)+3.*(2.5)-3);
err1=-1;
for i=1:length(N)
n=N(i);
x=2.5;
h=2.^(-n);
f=exp(-x).*(sin(x.^3)+sin(x.^2)-3.*x);
fprime = MyCenteredDifference(f, x, h);
err2=abs(fprime-trueValue);
ratio = err2/err1;
err1=err2;
if i==1
ratio=1;
end
fprintf('%5d\t%15.10f\t%15.10f\t%15.10f\n',n,I,err1,ratio)
end
_I'm getting an error for the "fprime = MyCenteredDifference(f, x, h);" line, and I don't know why it says "Array indices must be positive integers or logical values".
Please help me.
0 Kommentare
Antworten (1)
KSSV
am 8 Apr. 2022
You have not given/ shown us the function MyCenteredDifference, so we cannot check the function. But the error is simple and staright. In matlab array indices must be positive integers and logicals. In your case, you have voilated that crieteria and ended up with error.
EXample:
A = rand(1,10) ;
A(1) % no error
A(10) % no error
A(1.5) % error, index cannot be fraction
Use of logicals:
idx = A > 0.5 ;
A(idx) % no error
A(0) % error index cannot be double 0, 0 is not logical here
In the function, check where index is voilating the rule.
2 Kommentare
KSSV
am 8 Apr. 2022
Your f is not a function handle, it is a number as you have already substitued x in it. You may follow like shown below.
N=[5 6 7 8 9 10 11 12 13 14 15];
fprintf('%5s\t%15s\t%15s\t%15s\n','n','T(h)','En','En/E(n-1)')
trueValue = exp(-2.5).*(-sin((2.5).^3)-sin((2.5).^2)+2.*(2.5).*cos((2.5).^3)+3.*(2.5).^2.*cos((2.5).^3)+3.*(2.5)-3);
err1=-1;
f=@(x) exp(-x).*(sin(x.^3)+sin(x.^2)-3.*x); %<--- function handle
for i=1:length(N)
n=N(i);
x=2.5;
h=2.^(-n);
fprime = MyCenteredDifference(f, x, h);
err2=abs(fprime-trueValue);
ratio = err2/err1;
err1=err2;
if i==1
ratio=1;
end
fprintf('%5d\t%15.10f\t%15.10f\t%15.10f\n',n,i,err1,ratio)
end
function fprime = MyCenteredDifference(f, x, h)
fprime = (f(x+h) - f(x-h)) ./ (2*h);
end
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!