Nodes = rand(15,3);
Tetra = delaunay(X);
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,'CELL_DATA %s\nSCALARS %s float 1\nLOOKUP_TABLE default\n',num2str(nt),DataName);
s='%f\n';
fprintf(FID,s,Data);
 
fclose(FID);
%% Binary

fname='TetraBinary.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\nBINARY\n');
fprintf(FID,'DATASET UNSTRUCTURED_GRID\n');
 
fprintf(FID,'POINTS %d float\n',np);
P=[Nodes zeros(np,3-dim)];
fwrite(FID, P', 'float', 'b');
 
fprintf(FID,'\nCELLS %d %d\n',nt,nt*(dim+2));
fwrite(FID,[(dim+1)*ones(nt,1) Tetra-1]', 'float', 'b');
 
fprintf(FID,'\nCELL_TYPES %d\n',nt);
fwrite(FID,celltype(dim)*ones(nt,1), 'float', 'b');
 
fprintf(FID,'\nCELL_DATA %s\nSCALARS %s float 1\nLOOKUP_TABLE default\n',num2str(nt),DataName);
fwrite(FID, Data, 'float', 'b');

fclose(FID);