extract 2D matrix from 3D matrix and array of indi

2019-07-31 23:31发布

I cannot find out a satisfying answer. If A is a 3D matrix of size (m,n,k), Z is a 2D matrix of size mxn (integers with values between 1 and k), I want to extract S defined like this:

for i=1:m
    for j=n
        S(i,j) = A(i,j,Z(i,j));
    end
end

Is there an efficient (vectorized) way to do this?

Thank you in advance

1条回答
手持菜刀,她持情操
2楼-- · 2019-08-01 00:04

You can do it using linear indexing as follows:

S = reshape(A((1:m*n).' + m*n*(Z(:)-1)), m, n);
查看更多
登录 后发表回答