maanantai 18. elokuuta 2014

Exporting to vectorized PDF images in MATLAB

Keywords: painters, pdf, trisurf, white lines, patch

Ever tried to export nice looking, smoothly shaded pdf figures from MATLAB and ended up with something like this?
Would you prefer something like this?
If the answer to both questions is yes, then read on.

A plenty of forum posts in Mathworks' website propose different kinds of magic tricks to solve this problem. However, none of the tricks seemed to work for my case where I was drawing a surface with trisurf and exporting it to vectorized PDF with the following code.
trisurf(mesh.t',mesh.p(1,:)',mesh.p(2,:)',...
                  ufun(mesh.p(1,:),mesh.p(1,:))');
shading interp;
print -painters -dpdf -r600 vel.pdf
This always ended up with the annoying white lines as demonstrated in the first figure. Finally I realized that trisurf uses underneath the patch command to actually draw the triangles. I came up with a simple fix of setting up interpolated edge colors to every triangle drawn by the patch command as follows:
H = trisurf(mesh.t',mesh.p(1,:)',mesh.p(2,:)',...
                  ufun(mesh.p(1,:),mesh.p(1,:))');
set(H,'EdgeColor','interp');
shading interp;
print -painters -dpdf -r600 vel.pdf
This gives the beatiful plot in the second figure. For cropping the whitespace around the pdf I propose the usage of the linux command line tool pdfcrop.