Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.

1 次查看(过去 30 天)
Hello, I have some trouble with my Newton Raphson program with two variables. I'm stuck on something that displays the message written in the title and I don't understand what doesn't work. Indeed it looks like the dimensions of err(:,i) and of abs(X-Xold) aren't the same, but I don't understant why because for me X and Xold have the same dimension, and the dimension of err(:,i) is defined after that.
X0 = [1, 1];
maxIter = 100;
tolX = 1e-6;
X = X0;
Xold = X0;
for i = 1:maxIter
[f,j] = DM2(X);
X = X - inv(j)*f;
err(:,i) = abs(X-Xold); (The error is on this line)
Xold = X;
if(err(:,i)<tolX)
break;
end
end
Also, here is my function DM2 (I don't know if it could help):
function [fval,jacobian] = DM2(X)
% Define two variables
x = X(1);
y = X(2);
% Define f(x)
fval(1,1) = y - x^3 - 1;
fval(2,1) = -6*y + 2*x^3 + 10;
% Defining the jacobian
jacobian = [3*x^2, 1;
6*x^2 , -6];
If anyone has an advice or any tips on how to solve that problem that'ld great !!!
Have a nice day all :)

回答(1 个)

Walter Roberson
Walter Roberson 2020-5-26
inv(j)*f is going to return a column vector. Your original X0 is a row vector. Since R2016b, if you subtract a row vector and a column vector, MATLAB will subtract each element of the one from each element of the other -- so you would get back a 2 x 2 array instead of a 2 x 1 or 1 x 2.
The easiest fix is to make your x0 into a column vector.

Community Treasure Hunt

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

Start Hunting!

Translated by