The function "evaluate" solves the problem. Evaluating the expression at point 1 (or any other point depending on the problem) implicitly gives the empty cells in the expression.
clear; clc;
% Decision variables
x = optimvar('x',[5,1]);
% Empty expression
expr = optimexpr(size(x));
% Assignments for the expression
expr(1) = x(1);
expr(2) = x(2);
% Detect empty cells in the expression and remove them
inds = expr.evaluate(struct('x',ones(size(x)))) == 0; % Evaluate at point 1.
expr(inds) = [];
% Generate constraints from the expression
% if the empty expressions are not removed, the constraint 0 >= 5 is being generated!!!
cons1 = expr >= 5;