function x = independent(x)
%INDEPENDENT Create independent variable from dependent variable
%   Y = INDEPENDENT(X) returns a new independent variable Y from X.
%
%   Example:
%     a = dlarray(3);
%     grad = dlfeval(@fun,a);
%     function dy = fun(x)
%        y1 = x.^2;
%        y2 = independent(y1);
%        y = y1 + y2;
%        dy = dlgradient(y,x); % dy = 2*x
%     end
%
%   See also: dlgradient

%   Copyright 2019 The MathWorks, Inc.

fd = x.FormattedData;
x.FormattedData = [];
[fd, z] = extractData(fd);

if isa(z,'deep.internal.recording.RecordingArray')
    z = independent(z);
end

% Format is guaranteed not to have changed
fd = insertData(fd, z);
x.FormattedData = fd;
end
