Faster way to concatenate vectors repeatedly

Viewed 319

Is there a faster way to concatenate matrix like this code below? These lines of code will be called thousands of times, thus it's very time consuming. For 1658880 calls, I get 15 seconds for just one slice! (I have around 2000 slices, so total number of calls would be 1658880*2000 times!)

a=rand(1,100);
b=rand(1,100);
c=rand(1,100);
d=rand(1,100);

k=([b; b; b; d; ones(100); c; a; a; a]);

EDIT

Suggestion by Dev-iL (with repmat):

k=zeros(9,100);
k(1:3,:)=repmat(b,3,1);
k(4,:)=d;
k(5,:)=ones(size(a));
k(6,:)=d;
k(7:9,:)=repmat(a,3,1);

without repmat

k=zeros(9,100);
k(1,:)=b;
k(2,:)=b;
k(3,:)=b;
k(4,:)=d;
k(5,:)=ones(size(a));
k(6,:)=d;
k(7,:)=a;
k(8,:)=a;
k(9,:)=a;

With repmat, it's slower than the original code by 11 seconds. Without repmat, I actually get 15 seconds faster!

I'd appreciate any more suggestions and help! Thanks in advance!

1 Answers

Since in MATLAB data is stored in column-major order it is better to generate a,b,c,d as column vectors and concatenate them as:

a=rand(100,1);
b=rand(100,1);
c=rand(100,1);
d=rand(100,1);
one = ones(100);
k= [b b b d one c a a a];

Instead you can pre-allocate k and fill it as:

k = ones(100,108); %preallocation
%in the loop you can fill it:
k(:,1)=b;
k(:,2)=b;
k(:,3)=b;
k(:,4)=d;
k(:,105)=c;
k(:,106)=a;
k(:,107)=a;
k(:,108)=a;
Related