function data_save(fname, x, y, z)

   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   %
   % Function writes a 3d data-file for 3d contour, color, and mesh plots, and
   % 2d contour and color plots.
   %
   % Input
   %    fname: 3d data file-name (including path)
   %    x:     vector of x coordinates
   %    y:     vector of y coordinates
   %    z:     matrix of z coordinates
   %           z(i,j) = value of z corresponding to point (x(i), y(j))
   %
   % An example of how to call data_save is:
   %
   %    data_save("./sinc3d.txt", x, y, z);
   %
   % License:
   %    This document is released into the public domain.
   %
   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

   % Check size of z matrix
   [nx, ny] = size(z);
   if ( nx != length(x) || ny != length(y) )
      error("Size of z matrix not compatible with sizes of x and y vectors.");
   end

   % Write data file
   fid = fopen(fname, "w");
   fprintf(fid, "%13d %13d", nx, ny);
   fprintf(fid, "\n");
   fprintf(fid, "%+13.6e ", x);
   fprintf(fid, "\n");
   fprintf(fid, "%+13.6e ", y);
   fprintf(fid, "\n");
   for ( i = 1:nx )
      for ( j = 1:ny )
         fprintf(fid, "%+13.6e ", z(i,j));
      end
      fprintf(fid, "\n");
   end
   fclose(fid);
end

