bio_img_matlab

The MATLAB Blog

Practical Advice for People on the Leading Edge

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);
Ran in version 24.1.0.2689473 (R2024a) Update 6 Time for 10000000 horzcats is 0.650s Time for 10000000 vertcats is 0.747s
% 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);
Ran in version 25.2.0.3042426 (R2025b) Update 1 Time for 10000000 horzcats is 0.557s Time for 10000000 vertcats is 0.686s
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
ans = struct with fields:
CPUName: 'Apple M2 Pro' Clock: 'N/A' Cache: 65536 TotalMemory: 1.7180e+10 NumCPUs: 1 TotalCores: 10 OSType: 'macOS' OSVersion: '15.5' Hostname: 'uk-mcrouche-m'
|
  • print

댓글

댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.