'Matlab App built in runtime 9.10 runs significantly slower in runtime 9.7

I have an app I wrote in Matlab app designer, built in Matlab 2020a (v9.10 runtime environment). I have to compile it in v9.7 runtime though. When I do this it runs significantly slower. The function that runs the slowest is, conceptually:

Output = ones(length(A),length(B));
Temp = [];
for ii = 1:length(A)
  for jj = 1:length(B)
    Temp = [Temp; Output(ii,jj)];
  end
end

The above code runs for a total of 1.5 million to 2 million cycles. When I compile and run in v9.10, this bit of code is manageable, but in v9.7 there is a significant slowdown. I'm not sure this is fixable at this point, but I would like to give a more official reason for why this won't work.

Thanks.



Solution 1:[1]

The reason that it works faster in the newer MATLAB is that MATLAB improves with each release, and apparently between these two releases they managed to improve how the given code is compiled.

There are two big issues with the code that make it extremely slow:

  1. There is no preallocation, Temp grows with every loop iteration. This is slow. Preallocating will make this code much, much faster.

  2. The array Temp grows by concatenation, which is the slowest form of growing. The better way would be Temp(end+1) = Output(ii,jj);, which grows the underlying memory geometrically. See here for details.

Note that the code can be trivially vectorized as follows:

Temp = Output.';
Temp = Temp(:);

This will likely make the code faster in both versions of MATLAB.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1