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

1 view (last 30 days)
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.

Accepted Answer

Adam Danz
Adam Danz on 5 Aug 2020
"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));
% ^

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!