Transforming a vector in a one of predetermined length in Matlab -
i asking write following piece of matlab code in faster way. code doing following
(1) consider natural number n , column vector a of dimension mx1.
(2) if m>n keep first n elements of a
(3) otherwise add final zeros a nx1 vector
my attempt this:
n=4; a=[1 2 3 4 5]' if size(a,1)>n a=a(1:n); %keep first n elements else a=[a; zeros(size(n-size(a,1)),1)]; %add zeros n elements end do know faster ways?
you may try following alternative, @ best speed-up barely noticeable (and results vary slightly, depending on m , n). hard imagine being bottleneck - improving other part of code produce more significant benefit.
b = zeros(n,1); b(1:min(n,length(a))) = a(1:min(n,length(a)));