// Related Software: Scilab
// License     : BSD (4.4): https://fileexchange.scilab.org/licenses/7
// Functions   : OLS()
// Author (C)  : Mario MAGGI - Italy
// Release     : 1.0
// Date        : 2019-08-30
// Distribution: https://fileexchange.scilab.org/toolboxes/562000
// History     :
//   1.0 - 2019-08-30: first publication on FileExchange
//
function [q]=quantile(x,p)

    // given the data matrix x, this function computes the
    // matrix q of quantiles at levels corresponding to the
    // entries of p, which must be in (0,1]

    [lhs,rhs]=argn(0)
    if rhs<>2 then
        error(msprintf(gettext("%s: Wrong number of input arguments: %d expected.\n"),"quantile",2));
    end
    if x==[]|p==[] then q=[];return;end
    if max(p)>1|min(p)<=0 then
        error(msprintf(gettext("%s: Wrong value for input argument #%d: Must be in (%d,%d].\n"),"quantile",2,0,1))
    end
    if type(x)<>1 then
        error(msprintf(gettext("%s: Wrong type for input argument #%d: Numerical expected.\n"),"quantile",1))
    end
    x = x(:);
    lx = size(x,1);
    if min(p)<(1/lx) then
        warning(msprintf(gettext("%s: The input argument #%d contains elements < 1/n: replaced by 1/n"),"quantile",1))
        p = max(p,(1/lx));
    end
    x1 = gsort(x);
    x1 = x1($:-1:1);
    p = p*lx;
    q = x1(floor(p));
    q = matrix(q,size(p));
endfunction
