MATLAB is pretty good with vectors and matrices, but when it comes to "general arrays", you often have to switch to "general methods". When you are accustomed to the ease with which you manipulate matrices / vectors, it will seem really awkward, backward and not very convenient at all (in fact, these are very justified reasons for this, but this is a discussion at another time :).
The version below goes through each page through arrayfun (which runs faster than a regular loop for large matrices) and calls diag on each page:
% "flip" the array, so that 3rd dimension becomes the 1st (rows), and % the 1st dimension becomes the 3rd, so that each "page" is a regular % matrix. You want the diagonals of all these matrices. b = permute(a, [3 2 1]); % Now "loop" through the pages, and collect the matrix diagonal for each page c = arrayfun(@(ii)diag(b(:,:,ii)), 1:size(b,3), 'UniformOutput', false); % The above will output a cell-array, which you can cast back to % a numeric matrix through this operation: A = [c{:}];
source share