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

问题描述

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

我想出了以下代码,尽管根本不是完全正确的。我正在使用MATLAB 2019b。

%pseudo data
x = zeros(3,2,2);
y = ones(3,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

解决方法

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

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

我不确定您希望代码执行什么操作,特别是考虑到要比较全数字数组中的字符串时。这是一段满足您期望的代码:

textBox.Text = "some random value...";
var be = textBox.GetBindingExpression(TextBox.TextProperty);
if (be != null)
    be.UpdateSource();

这里的窍门是,如果给定页面(三维)上的所有元素均为零,则x = zeros(3,2,2); y = ones(3,2); positions = 2:4; y(positions) = 0; xy = cat(3,x,y); idx = ones(size(xy,3),1,'logical'); % initialise catching array for ii = 1:size(xy,3) if sum(nnz(xy(:,ii)),'all')==0 % If the third dimension is all zeros idx(ii)= false; % exclude it end end xy = xy(:,idx); % reindex to get rid of all-zero pages 为零。在这种情况下,请将其从sum(xy(:,ii),'all')==0中排除。然后,在最后一行中,只需使用logical indexing重新编制索引,以仅保留至少一个非零元素的页面。

您可以使用sum(a,[1 2])(即,矢量和)来更快地完成此操作,而无需循环:

idx