function [dict, label, dict_cell, label_cell] = generate_near_field_codebook2(N, d, lambda, eta, rho_min, rho_max,sector,S,uniform,grid_r)
    c = 3e8;
    theta = -sector + 2*sector/S : 2*sector/S : sector;
%     theta = -1 + 2/N : 2/N : 1;
    dict = cell(S, 1);
    label = cell(S, 1);
     Z = rho_max/ eta^2;%(2 * N * d)^2 / 2 / lambda / eta^2;
    kmin = floor(Z/rho_max) + 1;
    
     if uniform == 1
            kmax = grid_r-1;  %%%距离均匀划分的格点数
            r = zeros(1, kmax - kmin + 2);
            r(:,1) = (2 * N * d)^2 * 2 / lambda;
            r(:,2:end) = (kmax:-1:kmin)*Z/kmax;
     end
     
%      r = sort(r);
     
     for idx = 1:kmax - kmin + 2  
            dict{idx} = zeros(N, S);
            label{idx} = zeros(2, S);
        for t = 1 : S          
            dict{idx}(:, t) = sqrt(N)*near_field_manifold( N, d, c/lambda, r(idx), asin(theta(t)) );
            label{idx}(:, t) = [theta(t), r(idx)]';
        end
    end
    dict_cell = dict;
    label_cell = label;
    dict = merge(dict, kmax - kmin + 2  , N);
    label = merge(label, kmax - kmin + 2  , 2);
end

function B = merge(A, N, Q)
    S = zeros(1, N);
    for idx = 1:N
        S(idx) = size(A{idx}, 2);
    end
    B = zeros(Q, sum(S));
    for idx = 1:N
        B(:, sum(S(1:idx)) - S(idx) + 1: sum(S(1:idx))) = A{idx};
    end
end