# Plot 2D piecewise constant in matlab in a finite elements mesh

I need to generate a discontinuous plot (piecewise in each triangle) in matlab, something like:

This plot is from http://www.alecjacobson.com/weblog/?p=3616, but I don't understand how generate it.

I have two matrices corresponding to a triangular mesh of a domain (typical of finite elements method, that is, no overlaped triangles, the union of all triangles is equal to the domain...):

coord=[x1,y1;x2,y2;...;xnod,ynod]      % vertices of the mesh
ele  =[n1,n2,n3;n1,n2,n3;...;n1,n2,n3] % mesh conectivity


For example:

coord(1,:)=[x1,y1] are the coordinates of vertex 1 of the mesh (vertex of some triangle)
coord(2,:)=[x2,y2] are the coordinates of vertex 2 of the mesh (vertex of some triangle)
etc,

ele(1,:)=[n1,n2,n3] is the number of the vertices of triangle 1
ele(2,:)=[n1,n2,n3] is the number of the vertices of triangle 2
etc.


This way, for example,

coord(ele(4,:),:)=[x1,y1;x2,y2;x3,y3]


are the coordinates (x1,y1), (x2,y2) and (x3,y3) of the vertices of triangle 4.

The solution that I need to plot is a vector "u" which size is the number of triangles of the mesh (=number of rows of "elem"), because this solution is one constant over each triangle.

How can I plot this discontinuous solution?

I use typically the following approach. The idea is to make a new mesh where every vertex is duplicated so that each triangle has its own copy. Then you can use standard trisurf command to the resulting mesh structure.

p=coord';
t=ele';
x=p(1,:);
y=p(2,:);
P=[x(t(:));y(t(:))];
T=reshape(1:size(P,2),[3 size(P,2)/3]);
% create random u for testing
u=rand(size(P,2)/3,1);
tmp=[u';u';u'];
trisurf(T',P(1,:),P(2,:),tmp(:))


If you have PDE toolbox there is also a built in command for this called pdesurf.