主要内容

Resolve Error: Unable to Assign Expression During Automatic Differentiation

Issue

If you attempt to assign a value to a variable in a problem that uses automatic differentiation, you might get this error:

Convert left-hand side to expression before assignment.

The reason is that, for automatic differentiation calculations, MATLAB® represents symbolic variables using an internal expression object. For instance, MATLAB creates an internal expression object when you solve an ode object that has a JacobianMethod property value of "autodiff".

For example, suppose that the myFun function is involved in automatic differentiation calculations. In the myFun function, the y variable is initialized to a numeric array using the zeros function. If x is an expression object, the attempt in the for-loop to assign the expression involving x to the numeric array y throws an error.

function y = myFun(x)
y = zeros(size(x));
for i = 1:numel(x)
    y(i) = x(i)^2;
end
end

Possible Solutions

Before assigning a value to a variable, initialize that variable to be the same type as the variable used on the right-hand side of the assignment statement. The following two examples show how to specify the type of a variable to match another variable by using the "like" argument in a function call.

If you initialize your variable using a function that supports array creation, such as ones or zeros, you can call the function with the "like" argument. For example, initialize y as the same type of variable as x.

function y = myFun(x)
y = zeros(size(x),"like",x);
for i = 1:numel(x)
    y(i) = x(i)^2;
end
end

If you initialize your variable from data that you load or import, you can use the cast function with the "like" argument. For example, initialize y as the same type of variable as x.

y = cast(data,"like",x)

For more information, see Array-Creation Functions That Support Overloading.

See Also

Topics