It is great code, but you need to fix your bugs: in order to achieve the same column for your both images, you can fix number of columns with the following codes:
nrows = max(size(I1,1), size(I2,1));
ncols = max(size(I1,2), size(I2,2));
nchannels = size(I1,3);
extendedI1 = [ I1, zeros(size(I1,1), ncols-size(I1,2), nchannels); ...
zeros(nrows-size(I1,1), ncols, nchannels)];
extendedI2 = [ I2, zeros(size(I2,1), ncols-size(I2,2), nchannels); ...
zeros(nrows-size(I2,1), ncols, nchannels)];
Also, Binary images don't give us the minimum numbers for Hausdorff Distance. I checked your codes with several binary images and all of the times the max Hausdorff Distance numbers were the correct answer, not the minimum number.