function nodes = assignNodes(tree,X)
% Assign X rows into tree nodes given the tree as grown to this point

%   Copyright 2017-2020 The MathWorks, Inc

n = size(X,1);
nodes = ones(n,1);
if isempty(tree.var)
    return
end
for j=1:length(tree.var)
    if tree.var(j)==0
        continue
    end
    rows = find(nodes==j);
    varnum = tree.var(j);
    x = getSubset(X,rows,varnum);
    if ischar(x)
        x = cellstr(x);
    end
    if iscellstr(x) || isstring(x)
        x = strtrim(x);
    end
    cut = tree.cut(j);
    if isnan(cut)
        % Categorical split
        [~,level] = ismember(x,tree.catlevels{varnum});
        left = ismember(level,tree.leftclasses{j});
        nodes(rows(left)) = tree.left(j);
        right = ismember(level,tree.rightclasses{j});
        nodes(rows(right)) = tree.right(j);
    else
        % Continuous or ordinal split
        if iscategorical(x) && isordinal(x)
            cut = tree.catlevels{varnum}(cut);
        end
        nodes(rows(x<cut)) = tree.left(j);
        nodes(rows(x>=cut)) = tree.right(j);
    end
end
end

function x = getSubset(T,rows,cols)
% Get a subset of either a table or a matrix; if table get contents
if istable(T)
    x = T{rows,cols};
else
    x = T(rows,cols);
end
end