Array indices must be positive integers or logical values.

1 Ansicht (letzte 30 Tage)
Dominic Nightingale
Dominic Nightingale am 23 Okt. 2019
Beantwortet: Johannes Fischer am 23 Okt. 2019
clc;
clear all;
x=1;
h=10;
f = @(x) sin(((x^2+x)))
for n = 1:10
df(n-1) = (f(x+(h^(n-1)) - f(x)))/(h^n-1)
end
not sure what I am doing wrong to get this error.

Antworten (1)

Johannes Fischer
Johannes Fischer am 23 Okt. 2019
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);
end
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);

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by