Example code for the "Art of MATLAB" blog post of the same name.

polygonal(tN, pN, hN)

function [t, p, h] = polygonal(tN, pN, hN)
% POLYGONAL Compute three sequences of polygonal numbers
%
% [t, p, h] = polygonal(tN, pN, hN)
%
% Independently compute the entries in the triangular, pentagonal and
% hexagonal number sequences. Each input specifies the entry or entries
% to compute for a particular series:
%
% tN: Triangular numbers (returned in t)
% pN: Pentagonal numbers (returned in p)
% hN: Hexagonal numbers (return in h)
%
% Inputs may be scalars or vectors. Any input vector of length K returns
% in output of the K entries in the corresponding sequence.
%
% Example:
%
% [t, p, h] = polygonal(17, [3 6 9], 45)
%
% Returns:
% * The 17th triangular number in t
% * The 3rd, 6th and 9th pentagonal numbers in p
% * The 45th hexagonal number in h
%
% tN is required. pN and hN are optional.
%
% Polyongal numbers are a type of figurate number. See Wikipedia
% for a detailed definition: http://en.wikipedia.org/wiki/Figurate_number
%
% Example code developed to demonstrate how to manage multiple inputs and
% outputs in C# with Builder NE type safe APIs. See the "Art of MATLAB"
% blog article: "Mulitple Inputs and Outputs in Builder NE Type Safe APIs"
% at http://blogs.mathworks.com/loren/category/deployment/.
% One input: compute only triangular numbers
if nargin > 0
t = triangular(tN);
end
% Two inputs: also compute pentagonal numbers
if nargin > 1
p = pentagonal(pN);
end
% Three inputs: also compute hexagonal numbers
if nargin > 2
h = hexagonal(hN);
end
function t = triangular(n)
% TRIANGULAR Compute the Nth triangular number.
%
% If N is a vector of length K, compute K triangular numbers.
t = ( n.^2 + n ) / 2;
function p = pentagonal(n)
% PENTAGONAL Compute the Nth pentagonal number.
%
% If N is a vector of length K, compute K pentagonal numbers.
p = ( 3 * n.^2 - n ) / 2;
function h = hexagonal(n)
% HEXAGONAL Compute the Nth hexagonal number.
%
% If N is a vector of length K, compute K hexagonal numbers.
h = (2 * n .* ( 2*n - 1 ) ) / 2;