首页 > 解决方案 > 如何在循环中从 3D 矩阵中删除全零页面?

问题描述

如何在循环中从 3D 矩阵中删除全零页面?

我想出了下面的代码,虽然它不是“完全”正确的,如果有的话。我正在使用 MATLAB 2019b。

%pseudo data
x = zeros(3,2,2);
y = ones(3,2,2);
positions = 2:4;
y(positions) = 0;

xy = cat(3,x,y); %this is a 3x2x4 array; (:,:,1) and (:,:,2) are all zeros, 
                 % (:,:,3) is ones and zeros, and (:,:,4) is all ones
                 

%my aim is to delete the arrays that are entirely zeros i.e. xy(:,:,1) and xy(:,:,2),
%and this is what I have come up with; it doesn't delete the arrays but instead,
%all the ones.
for ii = 1:size(xy,3)
    
    for idx = find(xy(:,:,ii) == 0)

        xy(:,:,ii) = strcmp(xy, []); 

    end
    
end

标签: arraysmatlabfor-loopmultidimensional-array

解决方案


用于any查找具有至少一个非零值的切片的索引。使用这些索引来提取所需的结果。

idx = any(any(xy));   % idx = any(xy,[1 2]); for >=R2018b
xy = xy(:,:,idx);

推荐阅读