matlab 向量的复制,matlab - MATLAB:复制向量'n'次[重复] - 堆栈内存溢出

基于Abhinav的答案和一些测试,我写了一个总是比repmat()更快的函数!

它使用相同的参数,但第一个参数必须是向量而不是矩阵。

function vec = repvec( vec, rows, cols )

%REPVEC Replicates a vector.

% Replicates a vector rows times in dim1 and cols times in dim2.

% Auto optimization included.

% Faster than repmat()!!!

%

% Copyright 2012 by Marcel Schnirring

if ~isscalar(rows) || ~isscalar(cols)

error('Rows and cols must be scaler')

end

if rows == 1 && cols == 1

return % no modification needed

end

% check parameters

if size(vec,1) ~= 1 && size(vec,2) ~= 1

error('First parameter must be a vector but is a matrix or array')

end

% check type of vector (row/column vector)

if size(vec,1) == 1

% set flag

isrowvec = 1;

% swap rows and cols

tmp = rows;

rows = cols;

cols = tmp;

else

% set flag

isrowvec = 0;

end

% optimize code -> choose version

if rows == 1

version = 2;

else

version = 1;

end

% run replication

if version == 1

if isrowvec

% transform vector

vec = vec';

end

% replicate rows

if rows > 1

cc = vec(:,ones(1,rows));

vec = cc(:);

%indices = 1:length(vec);

%c = indices';

%cc = c(:,ones(rows,1));

%indices = cc(:);

%vec = vec(indices);

end

% replicate columns

if cols > 1

%vec = vec(:,ones(1,cols));

indices = (1:length(vec))';

indices = indices(:,ones(1,cols));

vec = vec(indices);

end

if isrowvec

% transform vector back

vec = vec';

end

elseif version == 2

% calculate indices

indices = (1:length(vec))';

% replicate rows

if rows > 1

c = indices(:,ones(rows,1));

indices = c(:);

end

% replicate columns

if cols > 1

indices = indices(:,ones(1,cols));

end

% transform index when row vector

if isrowvec

indices = indices';

end

% get vector based on indices

vec = vec(indices);

end

end

随意使用您的所有数据测试该功能并给我反馈。 当你找到一些甚至可以改进的东西时,请告诉我。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值