function [ ] = matrix2dat( filename, M, columnheads, N_plot)
%MATRIX2DAT Converts the given data to ".dat" format to use it with Latex
%tikzplot package. 
%
%function [ ] = matrix2dat( filename, M, columnheads, N_plot)
%   filename: filename for the new ".dat" file
%   M: The data to be export.d either as Matrix or Cell Array.
%   columnHeads: The columndescriptions as cell array of string
%   N_plot[optional, default=200]: Number of supportingpoints the export.
%                                   data should have

if isempty(regexpi(filename,'\w*\.(dat)$'))
    filename=[filename '.dat'];
end



if iscell(M)
   M_=[];
   for k=1:length(M)
      M_ = [M_ misc.mcv(M{k})]; 
   end
   M=M_;
end

if ~exist('N_plot', 'var')
    N_plot=200;
end

if size(M,1) > N_plot && N_plot > 0
    x=linspace(M(1,1), M(end,1), N_plot)';
    M=interp1(M(:,1), M(:,2:end), x);
    M=[x, M];
end

dlmwrite(filename, sprintf('%s\t',columnheads{:}), 'delimiter', '')
dlmwrite(filename, M, '-append', 'delimiter', '\t')