k = 15;
n = 1;
i = 0;
allK = [];
while k > n
if mod(k, 2) == 0
k = k / 2;
else
k = (k * 3) + 1;
end
i = i + 1;
allK(i) = k;
end
set(handles.mytext, 'String', sprintf('%d\n', allK));
Now allK grows iteratively. This is very expensive if the resulting array is large, e.g. for 1e6 elements. For your problem, the delay is negligible. A pre-allocation is not trivial here, because you cannot know how many elements are created by this function. But it is better to pre-allocate with a poor too large estimation:
allK = zeros(1, 1e6);
set(handles.mytext, 'String', sprintf('%d\n', allK(1:i)));
Alternatively you can assign a cell string to the 'String' property also instead of inserting line breaks:
set(handles.mytext, 'String', sprintfc('%d', allK(1:i)));
Best Answer