function z = complex(z,y)
%COMPLEX  Create complex array.
%   C = COMPLEX(A)
%   C = COMPLEX(A,B)
%
%   In the one-input syntax, the output Y has the same data format, if any,
%   as the input X.
%
%   In the two-input syntax, if both inputs are formatted, their data
%   formats must match.
%
%   See also COMPLEX, DLARRAY.

%   Copyright 2021-2023 The MathWorks, Inc.

if nargin == 1
    % If this file is modified to not be a standard unary element-wise
    % function, please also remove the following template tags.
    %!define $UnaryFunction complex($zdata)
    %!template $UnaryElementWiseTemplate
    % Code generated and inserted by deep.dev.generateDlarrayMethods.
    
    % Extract data to work on and create a template output object.
    [z, fdz, zdata] = extractUnaryElwiseData(z);
    
    zdata = complex(matlab.lang.internal.move(zdata));
    
    z = restoreUnaryElwiseData(z, ...
        matlab.lang.internal.move(fdz), ...
        matlab.lang.internal.move(zdata));
    %!template
else
    x = z;
    
    % Explicitly check whether sizes match or do scalar expansion; avoid
    % any complications with internal permutation handling or dimension
    % labels. Also, gpuArray/complex does support implicit expansion, so
    % checking here leads to a consistent behavior between CPU and GPU.
    if ~isscalar(x) && ~isscalar(y) && ~isequal(size(x), size(y))
        error(message('MATLAB:complex:inputSizeMismatch'))
    end
    dimsX = iGetDims(x);
    dimsY = iGetDims(y);
    
    % Disallow more complicated combinations of data formats here; may remove
    % this if complex for CPU starts supporting implicit expansion.
    if ~isempty(dimsX) && ~isempty(dimsY) && ~isequal(dimsX, dimsY)
        error(message('deep:dlarray:ComplexMatchFormat'))
    end
    
    % Binary function
    
    % If this file is modified to not be a standard binary element-wise
    % broadcast function, please also remove the following template tags.
    %!define $BinaryFunction complex($xdata, $ydata)
    %!template $BinaryBroadcastTemplate
    % Code generated and inserted by deep.dev.generateDlarrayMethods.
    
    % Extract data to work on and create a template output object.  If either
    % of the inputs are reusable it will be used as the template output.
    [z, fdz, xdata, ydata] = extractBinaryBroadcastData(...
        matlab.lang.internal.move(x), ...
        matlab.lang.internal.move(y));
    
    zdata = complex(matlab.lang.internal.move(xdata), matlab.lang.internal.move(ydata));
    
    z = restoreBinaryBroadcastData(z, ...
        matlab.lang.internal.move(fdz), ...
        matlab.lang.internal.move(zdata));
    %!template
end
end

function dimsX = iGetDims(X)
if isa(X, 'dlarray')
    dimsX = dims(X);
else
    dimsX = '';
end
end
