function xyz2asc(filename,X,Y,Z,noval,n)
    //Function to write a .asc or .txt regular grid form X Y Z matrixes
    //
    // Inputs
    //    filename, file name
    //    X,Y coordinate matrixes
    //    noval, remplace nan value in Z matrix
    //    n, data precision
    //
    //
    // Example
    //[X,Y]=meshgrid(0:.01:1);
    //Z=sin(X)+cos(Y);
    //xyz2asc('example.asc',X,Y,Z,-9999,2);
    //
    //
    //Author: Saúl Arciniega Esparza
    //zaul.ae@gmail.com
    // Institute of engineering UNAM
    
    // Matrix dimensions
    mx=size(X);
    my=size(Y);
    mz=size(Z);
    
    // Grid properties
    minx=min(X); //initial X coordinate
    miny=min(Y); //initial Y coordinate
    
    dxy=abs(X(1,1)-X(1,2)); //interval
    
    // Z matrix
    Z(isnan(Z))=noval; //nan values in the new file
    Z=flipdim(Z,1); //invert matrix rows
    
    // Output file
    //output X,Y precision
    if n==0
        dc='%.'+sprintf('%d',n)+'d';
    else
        dc='%.'+sprintf('%d',n)+'f';
    end
    
    fd=mopen(filename,'wt');
    // first lines
   mfprintf(fd,'ncols\t');
    mfprintf(fd,'%d\n',mz(2));
    mfprintf(fd,'nrows\t');
    mfprintf(fd,'%d\n',mz(1));
    mfprintf(fd,'xllcorner\t');
    mfprintf(fd,dc+'\n',minx);
    mfprintf(fd,'yllcorner\t');
    mfprintf(fd,dc+'\n',miny);
    mfprintf(fd,'cellsize\t');
    mfprintf(fd,'%.10f\n',dxy);
    mfprintf(fd,'NODATA_value\t');
    mfprintf(fd,dc+'\n',noval);
    
    wh=waitbar('Writing file...');
    // print Z values in output file
    for i=1:mz(1)
        for j=1:mz(2)
            if j==mz(2)
                mfprintf(fd,dc+'\n',Z(i,j));
            else
                mfprintf(fd,dc+'\t',Z(i,j));
            end
        end
        waitbar(i/mz(1),wh)
    end
    close(wh)
    mclose(fd);
    
endfunction
