Faster vector concatenation in MATLAB R2024b and later
At MathWorks, we are constantly working on making MATLAB faster. Most of the speed-ups that we achieve are discussed in the release notes but some slip through the net -- usually because they were fixed by a developer while they were in the process of working on some larger task. Here's one such optimization that found its way into MATLAB R2024b that I only recently discovered.
Consider two vectors that you want to concatenate:
a = [1 2 3 4];
b = [4 5 6 7];
c = [a b]; % Concatenate them horizontally
d = [a;b]; % Concatenate them vertically
These operations were made a little faster in R2024b and above. As you might imagine, such a small operation is very fast whatever version of MATLAB you use so we are going to repeat the concatenation 10 million times to make the point
N = 10000000;
% Run this in R2024a
tic
for i = 1:N
c = [a b];
end
totalHorzTime = toc;
tic
for i = 1:N
d = [a;b];
end
totalVertTime = toc;
myver = version;
out = "Ran in version " + myver;
out = out + sprintf("\nTime for %d horzcats is %.3fs\n",N,totalHorzTime);
out = out + sprintf("Time for %d vertcats is %.3fs\n",N,totalVertTime);
disp(out);
% Run this in R2025b
tic
for i = 1:N
c = [a b];
end
totalHorzTime = toc;
tic
for i = 1:N
d = [a;b];
end
totalVertTime = toc;
myver = version;
out = "Ran in version " + myver;
out = out + sprintf("\nTime for %d horzcats is %.3fs\n",N,totalHorzTime);
out = out + sprintf("Time for %d vertcats is %.3fs\n",N,totalVertTime);
disp(out);
This makes horzcat about 15% faster and vertcat around 8% faster in R2025b on this machine which, as you'll see below, is an M2 mac. On an older Intel Windows machine, I only saw a ~6% speed up in both cases so your mileage may vary.
It's not an enormous speed-up which is probably another reason why the developer chose not to include it in the release notes. However, I thought that some of you may be interested since every little helps!
Details of my machine
Using the popular cpuinfo add-on
cpuinfo


Comments
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.