Jac*_*cob 6 indexing matlab matrix multidimensional-array
考虑矩阵M和存储在列I和J中的一组下标.我需要访问I&J指定的元素而不将它们转换为线性索引(即使用sub2ind).例如
M = [1 2 3;4 5 6;7 8 9];
I = [1 1 1];
J = [1 2 3];
VALS = [1 2 3];
Run Code Online (Sandbox Code Playgroud)
此外,由于I&J非常庞大,因此执行以下操作是不可行的:
VALS = diag(M(I,J));
Run Code Online (Sandbox Code Playgroud)
为了示范,这不是我想要的,
VALS = M(sub2ind(size(M),I,J));
Run Code Online (Sandbox Code Playgroud)
基本上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
Run Code Online (Sandbox Code Playgroud)