"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)
Show older comments
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.
2 Comments
Stephen23
on 5 Aug 2020
"Think it might be a simple error but I just cant crack it."
To use MATLAB you have to learn the difference between array and matrix operations, otherwise your code will produce nonsense and you won't know why.
Accepted Answer
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));
% ^
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!