复制向量并在没有 for 循环的情况下将每个副本向下移动 1 行

Replicate vector and shift each copy by 1 row down without for-loop

我想复制一个向量 N 次以创建一个矩阵,每个副本向下移动 1 行。参见图像(第一列是向量 1 到 5)。如果不用for循环也能做到这一点就好了

到目前为止能够做到这一点 repmat(my_vector, 1, 5) 创建一个 N x 5 矩阵。

你可以用 toeplitz and tril;

a = [1 2 3 4 5]
out = tril( toeplitz(a) )

out = toeplitz(a, a*0)
%// out = toeplitz(a, zeros(size(a)) )  %// for large arrays

或者如果你不介意一些快乐的翻转:

out = flipud( hankel( flipud(a(:)) ) )

解决方案代码

这似乎是一种基于 repmat and bsxfun 的快速方法,因为下一节中列出的基准可能会让我们信服 -

%// Concatenate one zero at the end of a column vector version of the input vector.
%// Then, replicate the whole vector along columns to have a 2D matrix. 
%// Then "progressively" set elements from each column as zeros corresponding 
%// to the starting zeros of the desired output.
val = repmat([A(:);0],1,N).*bsxfun(@le,[1:N+1]',N:-1:1);  %//'

%// Chop-off at N x N length and reshape to have the final output
out = reshape(val(1:N*N),N,N);

基准测试

在本节中,我们将介绍针对本页列出的针对所述问题的各种方法的运行时基准测试。

基准代码-

%datasizes = [10 20 50 70 100 200 500 700 1000]; %// Set -1
datasizes = [1000 2000 5000 7000 10000];         %// Set -2
fcns = {'repvecshiftdown_flipud_hankel','repvecshiftdown_toeplitz',...
'repvecshiftdown_repmat_bsxfun','repvecshiftdown_tril_toeplitz'};%//approaches
tsec = zeros(numel(fcns),numel(datasizes));

for k1 = 1:numel(datasizes),
    A = randi(9,1,datasizes(k1)); %// Creare random input vector
    for k2 = 1:numel(fcns), %// Time approaches  
        tsec(k2,k1) = timeit(@() feval(fcns{k2}, A), 1);
        fprintf('\tFunction: %s (%3.2f sec)\n',fcns{k2},tsec(k2,k1));
    end
end

figure;  %% Plot Runtimes
plot(datasizes,tsec(1,:),'-rx'), hold on
plot(datasizes,tsec(2,:),'-bo')
plot(datasizes,tsec(3,:),'-k+')
plot(datasizes,tsec(4,:),'-g.')
set(gca,'xgrid','on'),set(gca,'ygrid','on'),
xlabel('Datasize (# elements)'), ylabel('Runtime (s)')
legend(upper(strrep(fcns,'_',' '))),title('Runtime')

关联函数代码(所有方法)-

function out = repvecshiftdown_repmat_bsxfun(A)
N = numel(A);
val = repmat([A(:);0],1,N).*bsxfun(@le,[1:N+1]',[N:-1:1]); %//'
out = reshape(val(1:N*N),N,N);
return;

function out = repvecshiftdown_tril_toeplitz(A)
out = tril( toeplitz(A) );
return;

function out = repvecshiftdown_toeplitz(A)
out = toeplitz(A, zeros(size(A)));
return;

function out = repvecshiftdown_flipud_hankel(A)
out = flipud( hankel( flipud(A(:)) ) );
return;

运行时图 -

设置 #1 [从 10 到 1000 个数据大小]:

设置 #2 [从 1000 到 10000 个数据大小]: