[英]How do I delete all-zero pages from a 3D matrix in a loop?
如何在循環中從 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
使用any
查找具有至少一個非零值的切片的索引。 使用這些索引來提取所需的結果。
idx = any(any(xy)); % idx = any(xy,[1 2]); for >=R2018b
xy = xy(:,:,idx);
我不確定您希望您的代碼做什么,特別是考慮到您正在比較全數字 arrays 中的字符串。 這是一段代碼,可以滿足您的要求:
x = zeros(3,2,2);
y = ones(3,2,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
如果給定頁面(第三維)上的所有元素都為零,則為零。 在這種情況下,將其從idx
中排除。 然后,在最后一行中,只需使用邏輯索引重新索引以僅保留至少包含一個非零元素的頁面。
您可以使用sum(a,[1 2])
更快地完成它,無需循環,即矢量維和:
idx = sum(nnz(xy),[1 2])~=0;
xy = xy(:,:,idx);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.