# Plot piecewise constant function over 2D triangle mesh as height field

## weblog/

I typically deal with piecewise linear functions defined over a triangle mesh (values defined per vertex). I can plot this over a 2d triangle mesh domain using the `trisurf` function:

trisurf(F,V(:,1),V(:,2),S);

I wrap this into my own function `tsurf` to make it easier to call since I call them so often:

``````tsurf(F,[V S]);
``````

Sometimes I deal with piecewise constant functions (values defined per triangle). To plot this I use:

``````tsurf(bsxfun(@plus,size(F,1)*(0:size(F,2)-1),(1:size(F,1))'),[V(F(:),:) repmat(S,size(F,2),1)]);
``````

Or broken down:

``````% positions of all "Corners"
C = V(F(:),:);
% Scalar field defined at corners
SC = repmat(S,size(F,2),1);
% new disjoint triangle indices into C for each original triangle
FC = bsxfun(@plus,size(F,1)*(0:size(F,2)-1),(1:size(F,1))');
% plot each triangle as piecewise linear function (each of which happens to be constant)
tsurf(FC,[C SC]);
``````