使用一组开始和结束索引索引数组

Index an array with a set of start and end indices

我有两个数组:

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



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

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

只是为了摆脱 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

然而,关于 运行 时间,如评论中所述,我没有测试过,但我怀疑它会更快。这里唯一的优点是结果数组不必在每次迭代时更新...

我通常会循环,但你可以这样做

%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{:}]

我应该提到这 比循环慢很多

使用 str2numsprintf 在数字数据和字符数据之间翻转以创建索引...这(在我的测试中)性能不如你循环已经为小型阵列完成,但对于大型阵列更快,因为内存分配处理得更好。

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

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 倍。

基准图

请注意,这取决于所使用的索引。在下面的代码中,我随机生成了每个 运行 的索引,因此您可能会看到情节有些跳跃。

但是,带有预分配的循环始终更快,而没有预分配的循环始终呈指数增长。


基准代码

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