function matlab_to_latex(matrix,rownames,...
		number_format,nan_empty,k_comma,outpath)

% function to print matlab matrices to latex table stubs
% (just the formatted numbers)

% open file handle
fileID = fopen(outpath,'w');

% get matrix dimensions
[rows,columns] = size(matrix);


% check that all rownames are given
if isempty(rownames) == 0 && length(rownames) ~= rows
	error('Number of rownames not equal to number of rows');
end

for row = 1 : rows
	% start up with rowname if specified
	if isempty(rownames) == 0
		line = [rownames{row} ' & '];
	else
		line = [ ];
	end
	for column = 1 : columns
		number = num2str(matrix(row,column),number_format);
		if mod(row,2) == 0 % even number -> p-values
			number1 = strcat('(',number);
			number = strcat(number1,')');
		end
		% insert comma as 1000s separator
		if k_comma == 1 && isempty(strfind(number, '.'))
			number = fliplr(regexprep(fliplr(number),'\d{3}(?=\d)', '$0,'));
		end
		if nan_empty == 1 && ~isempty(strfind(number,'NaN'))
			number = ' ';
		end
		if column < columns
			% fill line with formatted number & delimiter
			line = [line number  ' & '];
		else
			% put in line separator at last column
			line = [line number ' \\ '];
		end
	end
	line = regexprep(line,'\%','\\\%');
	% print line to file
	if row < rows
    	fwrite(fileID,[line 10],'char');
    else
    	fwrite(fileID,[line],'char');
    end
end

% close file handle
fclose(fileID);

end

