用一组开始和结束索引对数组进行索引

时间:2019-09-04 11:50:46

标签: matlab for-loop optimization indexing vectorization

我有两个数组:

timesteps = [1,3;5,7;9,10];
data = [1,2,3,4,5,6,7,8,9,10];

timesteps数组中的值描述了我需要data的哪些值。第一列开始,第二列结束。

例如在这里我想得到[1,2,3,5,6,7,9,10]

所以这段代码对我来说很好用,但是由于for循环的缘故,它的速度很慢... Matlab中是否有一个内衬,所以我可以摆脱for循环?

newData=[];
for ind=1:size(timesteps,1)
  newData=cat(2,newData,data(timesteps(ind,1):timesteps(ind,2)));
end



编辑: 使用Wolfie的解决方案,我得到了以下(非常好的)结果。 (我只使用了一个小数据集,通常是大数据集的50倍。)

(Mine)    Elapsed time is 48.579997 seconds.
(Wolfies) Elapsed time is 0.058733 seconds.

3 个答案:

答案 0 :(得分:5)

Irreducible's answer使用str2numsprintf在数字数据和char数据之间切换以创建索引...(在我的测试中)这与循环执行效果不佳(在我的测试中)对于小型阵列已经完成,但是对于大型阵列则更快,因为可以更好地处理内存分配。

您可以通过预分配输出并对其进行索引来避免循环中的连接,从而提高性能。对于大型阵列,这可以大大提高速度。

N = [0; cumsum( diff( timesteps, [], 2 ) + 1 )];
newData = NaN( 1, max(N) );
for ind = 1:size(timesteps,1)
    newData(N(ind)+1:N(ind+1)) = data(timesteps(ind,1):timesteps(ind,2));
end

下面的基准测试显示了如何始终保持更快的速度。

  • x轴:data中的元素数
  • y轴:时间以秒为单位
  • 假设:选择随机的索引子集,其中index的行比data少4倍。

基准测试图

benchmark

注意,这是可变的,具体取决于所使用的索引。在下面的代码中,我每次运行都会随机生成索引,因此您可能会看到绘图略有跳跃。

但是,具有预分配的循环始终较快,而没有预分配的循环始终呈指数级爆炸。


基准代码

T = [];
p = 4:12;
for ii = p
    n = 2^ii;
    k = 2^(ii-2);

    timesteps = reshape( sort( randperm( n, k*2 ) ).', 2, [] ).';
    data = 1:n;

    f_Playergod = @() f1(timesteps, data);
    f_Irreducible = @() f2(timesteps, data);
    f_Wolfie = @() f3(timesteps, data);

    T = [T; [timeit( f_Playergod ), timeit( f_Irreducible ), timeit( f_Wolfie )]];
end

figure(1); clf; 
plot( T, 'LineWidth', 1.5 );
legend( {'Loop, no preallocation', 'str2num indexing', 'loop, with preallocation'}, 'location', 'best' );
xticklabels( 2.^p ); grid on;

function newData = f1( timesteps, data )
    newData=[];
    for ind=1:size(timesteps,1)
      newData=cat(2,newData,data(timesteps(ind,1):timesteps(ind,2)));
    end
end
function newData = f2( timesteps, data )
    newData = data( str2num(sprintf('%d:%d ',timesteps')) );
end
function newData = f3( timesteps, data )
    N = [0; cumsum( diff( timesteps, [], 2 ) + 1 )];
    newData = NaN( 1, max(N) );
    for ind = 1:size(timesteps,1)
        newData(N(ind)+1:N(ind+1)) = data(timesteps(ind,1):timesteps(ind,2));
    end
end

答案 1 :(得分:2)

要摆脱for循环,您可以执行以下操作:

timesteps = [1,3;5,7;9,10];
data = [1,2,3,4,5,6,7,8,9,10];
%create a index vector of the indices you want to extract
idx=str2num(sprintf('%d:%d ',timesteps'));
%done
res=data(idx)

res =

 1     2     3     5     6     7     9    10

但是,关于运行时,如评论中所述,我尚未对其进行测试,但我怀疑它会更快。唯一的好处是不必每次迭代都更新结果数组...

答案 2 :(得分:1)

我通常会循环一圈,但是你可以做这样的事情

%take every 1st column element and 2nd column elemeent, use the range of numbers to index data
a=arrayfun(@(x,y) data(x:y),timesteps(:,1),timesteps(:,2),'UniformOutput',0) 
%convert cell array to vector
a=[a{:}]

我应该说,这比循环慢得多