Array indices must be positive integers or logical values.

1 回表示 (過去 30 日間)
Dominic Nightingale
Dominic Nightingale 2019 年 10 月 23 日
回答済み: Johannes Fischer 2019 年 10 月 23 日
clear all;
f = @(x) sin(((x^2+x)))
for n = 1:10
df(n-1) = (f(x+(h^(n-1)) - f(x)))/(h^n-1)
not sure what I am doing wrong to get this error.

回答 (1 件)

Johannes Fischer
Johannes Fischer 2019 年 10 月 23 日
The first entry in any kind of Matlab vector/array/matrix... is indexed with 1 (and not 0, as for example in C++). That is why you get an error in the first iteration of your for loop.
Two options:
adjust the indieces for df
for n = 1:10
df(n) = (f(x+(h^(n-1)) - f(x)))/(h^n-1);
or, in Matlab you can get rid or the for loop and matalb calculates the resulting array in a single line, in many cases this is faster than usinng for loops
n = 1:10;
df = (f(x+(h^(n-1)) - f(x)))/(h^n-1);


Help Center および File ExchangeMatrix Indexing についてさらに検索


Community Treasure Hunt

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

Start Hunting!

Translated by