MATLAB はベクトルと行列に非常に優れていますが、「一般的な配列」に関しては、「一般的な方法」に切り替える必要があることがよくあります。行列/ベクトルを簡単に操作することに慣れていると、これは本当にぎこちなく、後ろ向きで、あまり便利ではないように思えます (実際には非常に擁護できる理由がありますが、それについては別の機会に説明します :)。
以下のバージョンは、各ページを介してループしarrayfun
(これは、大きな行列の通常のループよりも高速です)、diag
各ページで次の呼び出しを行います。
% "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{:}];