[row,col] = find(~isnan(Z));
numRows = max(i);
numCols = max(j);
ZZ = zeros(numRows, numCols);
for r=1:numRows
    for c = 1:numCols
        ZZ(r,c) = Z(row(r),col(c));
    end
end

    