2016-04-07 111 views
1

考虑一维数组:y(1:20)和矩阵形式索引的集合:indx = [1,3; 7,12; 16,19]基于另一个开始和结束索引矩阵的索引矩阵

是否有一个整洁的方式来获得单元格数组:{y(1:3),y(7:12),y(16:19)}?

它很容易完成循环,但我很好奇知道一个简单和更简洁的方式来传递索引集合到1D数组。

回答

1

我不认为有使用循环的方法。您可以使用arrayfun作为简写,但:

arrayfun(@(from,to) y(from:to), indx(:,1), indx(:,2), 'uni', 0) 

在你的数据结果运行这

y = (1:20)*10; 
indx = [1,3;7,12;16,19]; 

celldisp(arrayfun(@(from,to) y(from:to), indx(:,1), indx(:,2), 'uni', 0)) 

ans{1} = 

    10 20 30 



ans{2} = 

    70 80 90 100 110 120 



ans{3} = 

    160 170 180 190 
+1

也许更具可读性:'arrayfun(@(从,到)Y(来自:到),INDX (:,1),indx(:,2),'uni',0)' –

+0

@丹,它看起来不错。我会试一试。非常感谢! –

+0

@ O'Neil是的,看起来更好。我会编辑它。 – Dan