3d matrix: how to use (row, column) pairs with 3rd dimension wildcard in MATLAB?

前端 未结 1 454
春和景丽
春和景丽 2020-12-21 11:18

I have a 3 dimensional matrix, and a list of (row, column) pairs. I would like to extract the 2 dimensional matrix that corresponds to the elements in those positions, proje

相关标签:
1条回答
  • 2020-12-21 11:18

    sub2ind is pretty much what you have to use here to convert your subscripts into linear indices (apart from manually computing the linear indices yourself). You can do something like the following which will convert the rows and cols to a linear index (in a 2D slice) and then it adds an offset (equal to the number of elements in a 2D slice) to these indices to sample all elements in the third dimension.

    sz = size(a);
    inds = sub2ind(sz(1:2), rows, cols);
    inds = bsxfun(@plus, inds, (0:(sz(3)-1)).' * prod(sz(1:2)));
    result = a(inds);
    

    And to actually compute the linear indices yourself

    inds = (cols - 1) * sz(1) + rows;
    inds = bsxfun(@plus, inds, (0:(sz(3) - 1)).' * prod(sz(1:2)));
    result = a(inds);
    

    Another option would be to permute your initial matrix to bring the third dimension to the first dimension, reshape it to a 2D matrix, and then use the linear index as the second subscript

    % Create a new temporary matrix
    anew = reshape(permute(a, [3, 1, 2]), size(a, 3), []);
    
    % Grab all rows (the 3rd dimension) and compute the columns to grab
    result = anew(:, (cols - 1) * size(a, 1) + rows);
    
    0 讨论(0)
提交回复
热议问题