【问题标题】:Index matrix based on another matrix of start and end indices基于另一个开始和结束索引矩阵的索引矩阵
【发布时间】:2016-04-07 09:56:40
【问题描述】:

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

有没有一种简洁的方法来获取单元格数组:{y(1:3), y(7:12), y(16:19)} ?

使用循环很容易完成,但我很想知道将索引集合传递给一维数组的简单且更简洁的方法。

【问题讨论】:

    标签: arrays matlab indexing


    【解决方案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
    

    【讨论】:

    • 也许更具可读性:arrayfun(@(from,to) y(from:to), indx(:,1), indx(:,2), 'uni', 0)
    • @ArnoldKlein 只知道如果有的话,这可能比简单的 for 循环的运行时效率低,因为 arrayfun 只是在后台执行一个循环。
    • @Dan,谢谢,很高兴知道。我正在学习“matlabian”编码方式,所以我试图避免任何循环或“快速而肮脏”的实现。
    猜你喜欢
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 2013-01-20
    • 2015-07-30
    • 2017-02-10
    相关资源
    最近更新 更多