My question might be trivial. I have a large 3D matrix (m by n by k elements) in MatLab and want to extract all diagonal slices and store them in another 3D array. For a better representation, I have attached a picture. the dashed lines are the diagonal slices I am looking for.
CodePudding user response:
Given a m x n x k
array a
use the following method to extract the slices into a cell array:
idx = repmat(reshape((0 : k - 1), 1, 1,[]) (1 : n), [m, 1, 1]);
result = accumarray(idx(:), a(:), [], @(x){reshape(x, m, 1,[])});
The slices have dimensions [m x 1 x y]
where y
ranges from 1
to min(n,k)
.
For old MATLAB versions use the following (bsxfun
instead of implicit expansion):
idx = repmat(bsxfun(@plus, reshape((0 : k - 1), 1, 1,[]), (1 : n)), [m, 1, 1]);
result = accumarray(idx(:), a(:), [], @(x){reshape(x, m, 1,[])});