【问题标题】:Fancy array access in MatlabMatlab中的花式数组访问
【发布时间】:2014-03-19 11:55:17
【问题描述】:

在 Python numpy 中,可以使用索引数组,如(取自教程):

data = array([[ 0,  1,  2,  3],
              [ 4,  5,  6,  7],
              [ 8,  9, 10, 11]])
i = array( [ [0,1],         # indices for the first dim of data
             [1,2] ] )
j = array( [ [2,1],         # indices for the second dim
             [3,3] ] )

现在,调用

data[i,j]                                 

返回数组

array([[ 2,  5],
       [ 7, 11]])

如何在 Matlab 中获得相同的结果?

【问题讨论】:

    标签: arrays matlab indexing


    【解决方案1】:

    我认为您将不得不使用 linear indexing ,您将从 sub2ind 函数中获得,如下所示:

    ind = sub2ind(size(data), I,J)
    

    示例:

    data =[ 0,  1,  2,  3
            4,  5,  6,  7
            8,  9, 10, 11]
    
    i = [0,1;
         1,2];
    
    j = [2,1;
         3,3]
    
    ind = sub2ind(size(data), i+1,j+1);
    data(ind)
    
    ans =
    
         2     5
         7    11
    

    注意我去了i+1j+1,这是因为与 Python 从0 开始索引不同,Matlab 从1 开始索引。

    【讨论】:

    • 感谢 Dan,它确实可以完成这项工作。不如 Python 漂亮,但它可以工作。我不知道sub2ind
    • @zeycus Matlab 以这种方式设计是有原因的,如果您可以为此使用与 Python 相同的语法,那么您将牺牲其他地方的优美语法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    相关资源
    最近更新 更多