function nd = ndims(obj)
%NDIMS   Number of dimensions.
%   N = NDIMS(X)
%
%   If X is formatted, NDIMS(X) returns the number of dimension labels,
%   even if some of the dimensions are trailing singleton dimensions.
%
%   See also SIZE, DLARRAY, DLARRAY/SIZE.

%   Copyright 2019 The MathWorks, Inc.

if hasdims(obj)
    nd = numel(obj.FormattedData.DimensionMetadata);
else
    viewToData = obj.ViewToDataMap;
    if isempty(viewToData)
        nd = ndims(obj.FormattedData.Data);
    else
        % Assumption: length(dataToView) >= ndims(obj.FormattedData.Data)
        data = obj.FormattedData.Data;
        
        for nd = length(viewToData):-1:2
            if size(data, viewToData(nd)) ~= 1
                break;
            end
        end
    end
end
end
