假设我有两个数组:
startIds = [x1, x2, x3]
endIds = [y1, y2, y3]
这两个数组长度相同,可以很长。我们可以假设(endIds(ii)-startIds(ii))对于所有位置ii都是相同的。有没有快速的方法来生成多个序列而不使用for循环?
startIds(1):endIds(1)
startIds(2):endIds(2)
startIds(3):endIds(3)
谢谢!
-Thang
答案 0 :(得分:2)
您可以使用arrayfun
:
sequences = arrayfun(@(i, j) (i:j), startIds, endIds, 'un', 0);
您将获得一个单元格数组sequences
,其中sequences{k} = startIds(k):endIds(k)
。
答案 1 :(得分:2)
这是我通过Mathworks获得的最快答案:
range = endIds(1) - startIds(1);
t3 = bsxfun(@plus, startIds(:), 0:range);
在撰写本文时,这是唯一比我的for循环版本更快的版本,它比使用arrayfun或ndgrid更快。在这里查看我的详细基准: http://www.mathworks.com/matlabcentral/answers/217205-fast-ways-to-generate-multiple-sequences-without-using-for-loop
答案 2 :(得分:1)
您也可以尝试使用矩阵,
首先获取每个条目与startIds中第一个条目之间的差异,
dif = startIds - startIds(1);
dif_m = repmat(dif,endIds-startIds+1,1);
然后制作第一个序列的矩阵
multi_seq = repmat((startIds(1):endIds(1))',1,length(startIds));
获取序列,
multi_seq = multi_seq + dif_m;