Is MATLAB confusing functions and arrays?

7 visualizzazioni (ultimi 30 giorni)
I have no idea what's going wrong with this code. I'm writing a simple function to find the root of a quadratic function using Newton's method:
function xNext = newtonMethod(x0, f)
xNext = x0;
for i = 1:20
func = f(xNext);
dx = diff(f(xNext));
xNext = xNext - (func / dx);
end
end
This may seem a bit convulted, but I've gone through several versions of this trying to figure out where I was going wrong. No matter what I do, I get the error message:
Error using /
Matrix dimensions must agree.
It seems to me like MATLAB is considering func and dx to be matrices when they're really just variables, but I'm not really sure. Any advice would be greatly appreciated. This has been a real head-scratcher for me.

Risposta accettata

Stephen23
Stephen23 il 7 Nov 2019
Modificato: Stephen23 il 7 Nov 2019
"Is MATLAB confusing functions and arrays?"
That can happen in certain circumstances, but that does not seem to be the case here.
Assuming that f is a function handle (that accepts a scalar and returns a scalar) and x0 is a scalar, then the badly named func
func = f(xNext);
will also be a scalar and therefore dx
dx = diff(f(xNext));
will be an empty array (this you can easily check yourself).
What do you expect to be the result of dividing a scalar by an empty array?
As its documentation states, diff returns the differences between element values, and so returns an array one element shorter than the input array (along the dimension operated along). It is unlikely that diff is useful for you, the way you are using it now.
  2 Commenti
Walter Roberson
Walter Roberson il 7 Nov 2019
To expand:
If you only pass f into newton's method then f has to be symbolic, or a function handle that can be invoked on a symbolic variable to produce a symbolic result. You would then diff() the symbolic expression of the function at the top of the file, and invoke the derivative on a particular x value in the loop.
If you cannot use the symbolic toolbox or the function f does not work for symbolic variables (such as if it has if statements or uses mod()) then you must pass in two function handles instead of one, with the second one evaluating the derivative.
diff() applied to numeric results from f() is not going work.
SlashyMacGuff
SlashyMacGuff il 7 Nov 2019
Thanks for your help. I was trying to take the derivative of f(x) with diff but I guess that's not exactly what it does. Poor understanding of the documentation on my part. Thanks for your help!

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by