"Index esceeds the number of array elements (1)". When clearly there is capacity for 201 spaces in the array, what is happening!?

1 次查看(过去 30 天)
clear all
clc
clf
f = @(x) ((x.^4+x.^2)/(x.^4+1)); % for this, f'' = f
hstep = 0.1;
x = -10:hstep:10;
n = length(x);
y = f(x); % values of the function on the mesh
ypp = zeros(n,1); % initialise the vector for the approximations
for i=2:n-1;
ypp(i) = (y(i+1)-2*y(i)+y(i-1))/(hstep^2);
end
figure;
plot(x,y);
xlabel('x')
axis square
hold on;
plot(x(2:end-1), ypp(2:end-1), 'or');
legend('y', 'ypp','Location', 'north')
Think it might be a simple error but I just cant crack it.

采纳的回答

Adam Danz
Adam Danz 2020-8-5
"Index esceeds the number of array elements (1)". When clearly there is capacity for 201 spaces in the array, what is happening!?
Not so clear to me. Running the code from your question, y equal 1.0126. It's a scalar value, not a vector.
The first line of the loop tries to pull the 3rd value from y but there is only 1 value.
for i=2:n-1;
ypp(i) = (y(i+1)-2*y(i)+y(i-1))/(hstep^2);
% ^^^^^^ ^^^^
end
To get a vector output from f(), repalce / with ./
f = @(x) ((x.^4+x.^2)./(x.^4+1));
% ^

更多回答(0 个)

类别

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

标签

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by