Append third column of zeros to MATLAB matrix, but only if it doesn't already exist

Alec Jacobson

September 22, 2012

weblog/

Say I have input to a function which might be a list of (x,y) positions or a list of 3d (x,y,z) positions. To keep my function simple I may want to just treat the 2d input as 3d by appending z=0 to each point. This may be easily and safely achieved in a number of ways, but I think this is the shortest. Say that my list of potentially (x,y) or (x,y,z) positions is in an n by 2 or 3 matrix V. Then I can append a column 0s or do nothing to the matrix (depending on the size) with the following call:
V(:,end+1:3) = 0;