Error: Index in position 1 is invalid. Array indices must be positive integers or logical values.

1 次查看(过去 30 天)
I am attempting to evaluate the nth derivative, at the ith x value, and store it. The motivation for this is to calculate the error that arises from approximating the Runge function using Chebyshev points.
My code:
syms x
func = 1 / (1 + 25*x^2);
Errs = zeros(17,200);
i = 0;
j = 0;
for n = 10:10:170
for x1 = -1:0.001:1
g = diff(func,n+1);
Err = (1 / ((2^n)*(factorial(n+1))))*(vpa(subs(g,x,x1)));
Errs(i,j) = Err;
j = j + 1;
end
i = i + 1;
end
%n=10
plot(xx, Errs(0))
I get the error found in the title. I have very little experience with Matlab, but some experience with other programming languages. How are my indices negative? I define i and j to be equal to zero and increment by 1, so I am not sure where these negative values are coming from. Any help is appreciated, thank you.

采纳的回答

Star Strider
Star Strider 2019-9-12
The problem is that ‘i’ and ‘j’ are initially both 0.
I also did what I could to speed up your code, although it is still extremely slow:
syms x
func(x) = 1 / (1 + 25*x^2);
Errs = zeros(17,200);
i = 1;
j = 1;
n = 10:10:170;
x1 = -1:0.001:1;
for k1 = 1:numel(n)
for k2 = 1:numel(x1)
g = diff(func,n(k1)+1);
Err = (1 / ((2^n(k1))*(factorial(n(k1)+1))))*g(x1(k2));
Errs(i,j) = Err;
j = j + 1;
end
i = i + 1
end
My changes were to make ‘func’ an actual function, so that now ‘g’ is also a function, meaning that you can eliminate the subs call, and the vpa call, that is unnecessary (except possibly with respect to the output of your code at the end).

更多回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by