Inner matrix dimensions must agree error message,

Hi,
I'm getting an error message that says inner matrix dimensions must agree, but I checked both matrices and they seem fine -- it's just a 2x2 matrix left-multiplying with a 2x1 matrix.
Here's the error message:
Error using *
Inner matrix dimensions must agree.
Error in Root_finding_practice (line 78)
x(:,i+1) = x(:,i) - ( inv( H( x(:, i) ) ) * J( x(:,i) ) ); % Newton's method in 2 variables
And here's the piece of the code:
J = @(x) [ cos( x(2) ), -x(1) * sin( x(2) ) ]; % Jacobian of f
H = @(x) [ 0, -sin( x(2) ); % Hessian matrix of 2nd derivatives
-sin( x(2) ), -cos( x(2) ) * x(1) ];
% An initial guess at a multivariable root:
x = [1; 1];
for i = 1:100 % The for-loop should stop when the function tolerance is satisfied
x(:,i+1) = x(:,i) - ( inv( H( x(:, i) ) ) * J( x(:,i) ) ); % Newton's method in 2 variables
What am I missing?
Thanks,

 Respuesta aceptada

Adam Danz
Adam Danz el 22 de Sept. de 2020
Editada: Adam Danz el 22 de Sept. de 2020
You can either perform element-wise multiplication with implicit expansion
x(:,i) - inv(H(x(:, i)) .* J(x(:,i)))
% add this ^
however that will produce a 2x2 output which will cause an error when you index it into
x(:,i+1) =
or you can perform matrix multiplication
H(x(:, i)) is a 2x2 matrix, J(x(:,i)) is a 1x2 matrix. If you multiply these matricies, you either need to transpose the J term or switch the two terms
H(x(:, i)) * J(x(:,i)).' % result is 2x1 matrix
% or
J(x(:,i)) * H(x(:, i)) % result is a 1x2 matrix
but matrix inversion using inv() requires the use of a square matrix and neither of those fulfill that requirement.
So, you've got some thinking to do regarding what the output should be and how you'll store it.

4 comentarios

Noob
Noob el 22 de Sept. de 2020
Editada: Noob el 22 de Sept. de 2020
Ah, yes, J was of size 1x2, so I just transposed it.
I'm just inverting the 2x2 Hessian matrix, so it's fine.
Thanks!
Adam Danz
Adam Danz el 22 de Sept. de 2020
Ahhh, right. All of those spaces between the brackets threw me off.
Noob
Noob el 22 de Sept. de 2020
haha, yeah, I like those spaces. it's kinda weird but it makes it more readable to me.
Have a great night / day, Adam!
Adam Danz
Adam Danz el 22 de Sept. de 2020
Editada: Adam Danz el 22 de Sept. de 2020
Thanks; and no problem with the spaces! You'll see lots of style manuals out there suggesting best practices when writing code that will be used by more than 1 person but it's fine to come up with a style that makes sense to you. Just today I was told by a friend that I write too many comments in my code 🙄.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Productos

Versión

R2017a

Etiquetas

Preguntada:

el 22 de Sept. de 2020

Editada:

el 22 de Sept. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by