"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.
Nathan Barnes
Nathan Barnes 2020 年 8 月 6 日
  • alright bro chill, im learning, thanks for the link tho :)

サインインしてコメントする。

採用された回答

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 Center および File ExchangeMATLAB についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by