function t = array2table(x,varargin) %#codegen
%ARRAY2TABLE Convert homogeneous array to table.
%   T = ARRAY2TABLE(A) converts the M-by-N array A to an M-by-N table T.
%   Each column of A becomes a variable in T.
%
%   NOTE:  A can be any type of array, including a cell array.  However, in that
%   case you probably want to use CELL2TABLE instead.  ARRAY2TABLE creates the
%   variables in T from each column of A.  If A is a cell array, ARRAY2TABLE
%   does not extract the contents of its cells -- T in this case is a table each
%   of whose variables is a column of cells.  To create a table from the
%   contents of the cells in A, use CELL2TABLE(A).
%
%   T = ARRAY2TABLE(X, 'PARAM1', VAL1, 'PARAM2', VAL2, ...) specifies optional
%   parameter name/value pairs that determine how the data in X are converted.
%
%      'VariableNames'  A string array or cell array of character vectors
%                       containing variable names for T.  The names must be
%                       valid MATLAB identifiers, and must be unique.
%      'RowNames'       A string array or cell array of character vectors
%                       containing row names for T.  The names need not be
%                       valid MATLAB identifiers, but must be unique.
%
%   See also TABLE2ARRAY, CELL2TABLE, STRUCT2TABLE, TABLE.

%   Copyright 2012-2019 The MathWorks, Inc.

if ~isempty(coder.target)
    % codegen, redirect to codegen specific function and return
    t = matlab.internal.coder.array2table(x, varargin{:});
    return
end

if ~ismatrix(x)
    error(message('MATLAB:array2table:NDArray'));
end
[nrows,nvars] = size(x);

if nargin == 1
    rownames = {};
    supplied.VariableNames = false;
    supplied.RowNames = false;
else
    pnames = {'VariableNames' 'RowNames'};
    dflts =  {            {}         {} };
    [varnames,rownames,supplied] ...
        = matlab.internal.datatypes.parseArgs(pnames, dflts, varargin{:});
end

if ~supplied.VariableNames && (nvars > 0) % skip nvars==0 for performance
    baseName = inputname(1);
    if isempty(baseName) 
        varnames = matlab.internal.tabular.defaultVariableNames(1:nvars);
    else
        if nvars == 1
            varnames = {baseName};
        else
            varnames = matlab.internal.datatypes.numberedNames(baseName,1:nvars);
        end
    end
end

if nvars == 0
    % Performant special case to create an Nx0 empty table.
    t = table.empty(nrows,0);
    % Assign the supplied var names just to check for the correct number (zero) and
    % throw a consistent error. No need to check for conflicts with dim names.
    if supplied.VariableNames, t.Properties.VariableNames = varnames; end
    if supplied.RowNames, t.Properties.RowNames = rownames; end
else
    % Each column of X becomes a variable in T. No need to check if they are all the
    % same height, they are all columns in one array.
    vars = mat2cell(x,nrows,ones(1,nvars));
    t = table.init(vars,nrows,rownames,nvars,varnames);
end