Why am i getting this error message? "Array indices must be positive integers or logical values."

1 Ansicht (letzte 30 Tage)
x = 120;
for n=1:10
f= (x(cosh(600/x) -12)-108);
x_1 = x-(f/diff(f))
x=x_1;
end
Array indices must be positive integers or logical values.

Akzeptierte Antwort

Bjorn Gustavsson
Bjorn Gustavsson am 26 Okt. 2021
In matlab (and most other programming-languages) you will have to write out the multiplication-operator (* for matrix multiplication or .* for elementwise multiplication). The way you write:
x(cosh(600/x)-12)
Will be interpreted as the cosh(600/x)-12th element of the matrix x. Note here that 600/x would be a right-matrix-division, for elementwise division you will have to use ./.
Most likely you want:
f= (x*(cosh(600/x) -12)-108);
Then you will have a problem with the next line too, because f is now a scalar which make the function diff return an empty array, [], so you will have to do something about that.
If you are very new to matlab take a trip through the on-ramp courses on the Matlab web-site.
HTH
  5 Kommentare
Bjorn Gustavsson
Bjorn Gustavsson am 26 Okt. 2021
Yes, your f is a scalar - and if you check the help and documentation of diff you will see:
help diff
DIFF Difference and approximate derivative.
DIFF(X), for a vector X, is [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)].
DIFF(X), for a matrix X, is the matrix of row differences,
[X(2:n,:) - X(1:n-1,:)].
The diff-function expects an array as input. You call it with a scalar, which causes diff to return an empty array. To my eyes it seems as if you want to implement a Newton-solver, for that you want to divide with the derivative of your function. I suggest you introduce a new variable, perhaps named dfdx that you assign the derivative of the function whos value you assign to f. That should be straightforward for you with pen and paper. Alternatively you could calculate a numerical estimate of the derivative, but that is more programming.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by