Why am I getting Error "Array indices must be positive integers or logical values"?
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (1 件)
KSSV
2022 年 4 月 8 日
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 件のコメント
KSSV
2022 年 4 月 8 日
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
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!