"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.
  댓글 수: 2
Stephen23
Stephen23 2020년 8월 5일
"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.

댓글을 달려면 로그인하십시오.

채택된 답변

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