I found a solution:
For static text boxes one may use the 'Extent' UI property (http://www.mathworks.com/help/matlab/ref/uicontrol-properties.html#property_extent) to get the preferred size of the text box.
For an edit box this unfortunately returns the current visible size and not the preferred size (Text 'Extent' property doesn't contain the correct size). The preferred size can be gotten by invoking the java UI calls (Matlab components are just (mostly?) wrapped java swing components). Use the findjobj function (http://www.mathworks.com/matlabcentral/fileexchange/14317-findjobj-find-java-handles-of-matlab-graphic-objects) to get the java handle of the edit box, and get the preferred size of the box.
Code to achieve automatic font resizing (such that the maximum font size that still fits the entire string is used):
% --- Executes on key press with focus on edit1 and none of its controls.
function edit1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
H = hObject;
position = get(H,'Position');
width = position(3);
javaH = findjobj(H);
for FontSize = 48:-2:12
javaH.setFont(javaH.getFont().deriveFont(FontSize));
prefWidth = javaH.getPreferredSize.getWidth;
if prefWidth < width
break; % Escape loop: for FontSize
end
end
I used the java method to change the font size as I noticed that the preferred width call would be incorrect (delayed by 1 iteration?) when using the Matlab set(H,'FontSize',FontSize) call.