Nodes = rand(15,3);
Tetra = delaunay(Nodes);
DataName='Testdata';
Data=ones(size(Tetra,1),1);

%% ASCII - working
fname='TetraAscii.vtk';

[np,dim]=size(Nodes);
[nt]=size(Tetra,1);
celltype=[3,5,10];

FID = fopen(fname,'w+');
fprintf(FID,'# vtk DataFile Version 2.0\nUnstructured Grid Example\nASCII\n');
fprintf(FID,'DATASET UNSTRUCTURED_GRID\n');
 
fprintf(FID,'POINTS %d float\n',np);
s='%f %f %f \n';
P=[Nodes zeros(np,3-dim)];
fprintf(FID,s,P');
 
fprintf(FID,'CELLS %d %d\n',nt,nt*(dim+2));
s='%d ';
for k=1:dim+1
    s=horzcat(s,{' %d'});
end
s=cell2mat(horzcat(s,{' \n'}));
fprintf(FID,s,[(dim+1)*ones(nt,1) Tetra-1]');
 
fprintf(FID,'CELL_TYPES %d\n',nt);
s='%d\n';
fprintf(FID,s,celltype(dim)*ones(nt,1));
 
fprintf(FID,'\nCELL_DATA %s', num2str(nt));
fprintf(FID,'\nSCALARS %s float', DataName);
fprintf(FID,'\nLOOKUP_TABLE default\n');
s='\n%f\n';
fprintf(FID,s,Data);
 
fclose(FID);
%% Binary

fname='TetraBinary.vtk';

[np,dim]=size(Nodes);
[nt]=size(Tetra,1);
celltype=[3,5,10];

% Open file and write the header
FID = fopen(fname,'w+');
fprintf(FID, '# vtk DataFile Version 2.0\n');
fprintf(FID, 'Unstructured Grid Example\nBINARY\n');
fprintf(FID, 'DATASET UNSTRUCTURED_GRID\n');

% Write the points
fprintf(FID, '\nPOINTS %d float\n', np);
P=[Nodes zeros(np,3-dim)]';
fwrite(FID, P, 'float', 'b');

% Write the cell definitons as INTEGERS because they are indices
fprintf(FID,'\n\nCELLS %d %d\n',nt,nt*(dim+2));
fwrite(FID,[(dim+1)*ones(nt,1) Tetra-1]', 'int', 'b');
 
% Write the integer cell types as INTEGERS because they are ID Types
fprintf(FID,'\n\nCELL_TYPES %d\n',nt);
fwrite(FID,celltype(dim)*ones(nt,1), 'int', 'b');

% Write the data array
fprintf(FID,'\n\nCELL_DATA %d\n', nt);
fprintf(FID, 'SCALARS %s float %s', DataName);
fprintf(FID, '\nLOOKUP_TABLE default\n');
fwrite(FID, Data, 'float', 'b');

% Close the file handle
fclose(FID);