h=magic(6);
out = zeros(size(h,1),size(h,2),3); % Initialise output
out(:,:,1) = h; % Copy the green
for ii = 1:size(h,1)
for jj = 1:size(h,2)
% out(ii,jj,1) = h(ii,jj); % Green bit
% For orange, sum the row and column. Note the .' transpose,
% otherwise implicit broadcasting on the plus will create a matrix.
% Finally remove the green cell twice,
% as you added it in both row and column
out(ii,jj,2) = sum(h(ii,:)+h(:,jj).') - h(ii,jj)*2;
% Sum everything for yellow, and subtract the orange and green
out(ii,jj,3) = sum(h,'all') - out(ii,jj,2) - h(ii,jj)
end
end
这将生成一个 3D 输出矩阵,即它与输入矩阵的大小相同,其中绿色、橙色和黄色部分各有 3 页。请参阅代码中的 cmets 了解其作用。
感谢flawr your comment 提高黄色求和的速度。