MATLAB: Failure to open a Figure with a calculated figure number

figure numberfigure opening failurehg1hg2Image Processing ToolboxintegerMATLAB

Problem description
I am working with Matlab and the Image Processing toolbox.
At some point in a version update string, a figure number specified in an equation has begun to fail. I stripped the action down to the following annotated extract of my larger script, and it consistently fails (on my machine, at least), even after an overload re-installation of Matlab and the toolbox.
%%Clearing the decks for action
clc
clearvars
%%Verifying a figure can indeed be opened and closed
figure(31); close
uu = figure(31); % successfully opens the figure in this manner
disp(['IntegerHandle: ' uu.IntegerHandle]) % it's 'on', even as one wants
disp(['Number: ' num2str(uu.Number)]) % it's 31, the right value
figure(31); close(31); clear uu % workspace is clear now
%%Let's use an indirectly specified figure number now...
i=1;
fig_num = int16(30+i); % I even cast this as int16 in an attempt to make
% it work. int8 did not work either.
disp(['Figure number ' num2str(fig_num)])
whos fig_num % It's a 1x1 array of 2 Bytes, Class int16
%%Fine. That all worked. But now, ...
figure(i) % Figure 1 opens all right, but...
figure(fig_num) % figure(fig_num) will not.
% Fails!
With following information (in red), though of course not commented:
% Error using figure
% First argument must be a figure object or a positive Integer
% Error in trash_to_try_figure_number_failure (line 27)
% figure(fig_num) % figure(fig_num) will not.

Best Answer

The error message means, that the value must be an integer, not the class of the input. So simply omit the int16() to create a normal double:
i = 1;
fig_num = 30 + i;
figure(fig_num)
[EDITED] Because this works as expected, the problem is somewhere else: In the older graphics engine "HG1" used until R2014a, this worked:
n = int8(8); figure(n)
In HG2, this does not work anymore and the figure number must be provided as double:
n = int8(8); figure(double(n)) % Or use double directly
Note, that figure handles are more reliable as figure numbers, see Image Analyst's answer.