PDA

查看完整版本 : 使用下标访问值而不使用sub2ind


poster
2019-12-10, 16:49
考虑矩阵M和存储在列I和J中的一组下标。我需要访问I&J指定的元素,而无需将它们转换为线性索引(即,使用sub2ind (http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/sub2ind.html) )。例如

M = [1 2 3;4 5 6;7 8 9]; I = [1 1 1]; J = [1 2 3]; VALS = [1 2 3]; 另外,由于I&J 庞大 (https://stackoverflow.com/questions/1144929/learning-decision-trees-on-huge-datasets) ,因此执行以下操作是不可行的:

VALS = diag(M(I,J)); 为了演示,这不是我想要的,

VALS = M(sub2ind(size(M),I,J)); 实际上sub2ind似乎要花费很多时间,现在我正在寻找无需将下标转换为索引即可访问这些元素的方法。只要比使用sub2ind的方法更快,任何其他方法都是可行的。


回答:
这可能比使用SUB2IND更快:

[r,c] = size(M); % Get the size of M vals = M(I+r.*(J-1)); % Compute a linear index with vector operations

更多&回答... (https://stackoverflow.com/questions/1146719)