Octave/Matlab: 扩展一个向量使它重复自己?

有没有办法通过让向量重复来扩展它?

>v = [1 2];
>v10 = v x 5; %x represents some function. Something like "1 2" x 5 in perl

那么 v10就是:

>v10
1 2 1 2 1 2 1 2 1 2

这应该适用于一般情况,而不仅仅适用于[12]

55959 次浏览

The function you're looking for is repmat().

v10 = repmat(v, 1, 5)

Obviously repmat is the way to go if you know in which direction you want to expand the vector.

However, if you want a general solution that always repeats the vector in the longest direction, this combination of repmat and indexing should do the trick:

 v10=v(repmat(1:length(v),1,5))

Although late, I am posting this because this turned out to be the most popular answer to a similar question here.

This is a Faster Method Than repmat or reshape by an Order of Magnitude

One of the best methods for doing such things is Using Tony's Trick. I came across this trick in one of the Electrical Engineering course lectures notes of Columbia University. Repmat and Reshape are usually found to be slower than Tony's trick as it directly uses Matlabs inherent indexing. To answer you question,

Lets say, you want to tile the row vector r=[1 2 3] N times like r=[1 2 3 1 2 3 1 2 3...], then,

c=r'
cc=c(:,ones(N,1));
r_tiled = cc(:)';

This method has significant time savings against reshape or repmat for large N's.

I conducted a small Matlab test to check the speed differential between repmat and tony's trick. Using the code mentioned below, I calculated the times for constructing the same tiled vector from a base vector A=[1:N]. The results show that YES, Tony's-Trick is FASTER BY AN ORDER of MAGNITUDE, especially for larger N. People are welcome to try it themselves. This much time differential can be critical if such an operation has to be performed in loops. Here is the small script I used;

N= 10 ;% ASLO Try for values N= 10, 100, 1000, 10000


% time for tony_trick
tic;
A=(1:N)';
B=A(:,ones(N,1));
C=B(:)';
t_tony=toc;
clearvars -except t_tony N


% time for repmat
tic;
A=(1:N);
B=repmat(A,1,N);
t_repmat=toc;
clearvars -except t_tony t_repmat N

The Times (in seconds) for both methods are given below;

  • N=10, time_repmat = 8e-5 , time_tony = 3e-5
  • N=100, time_repmat = 2.9e-4 , time_tony = 6e-5
  • N=1000, time_repmat = 0.0302 , time_tony = 0.0058
  • N=10000, time_repmat = 2.9199 , time_tony = 0.5292

My RAM didn't permit me to go beyond N=10000. I am sure, the time difference between the two methods will be even more significant for N=100000. I know, these times might be different for different machines, but the relative difference in order-of-magnitude of times will stand. Also, I know, the avg of times could have been a better metric, but I just wanted to show the order of magnitude difference in time consumption between the two approaches. My machine/os details are given below :

Relevant Machine/OS/Matlab Details : Athlon i686 Arch, Ubuntu 11.04 32 bit, 3gb ram, Matlab 2011b