how to remove the zeros inside a 3D matrix?
Afficher commentaires plus anciens
AA,
I have a 3D matrix
Xroot(z,w,k) (10x33x402).
The problem is, for example Xroot(1,1,:) it contians 400 zeros and just 2 needed values.
and this for most of Xroot(z,w,:).
Xroot(1,1,:)
ans(:,:,1) =
69.8033
ans(:,:,2) =
83.5743
ans(:,:,3) =
0
ans(:,:,4) =
0
ans(:,:,5) =
0
etc...
______________ % another example
Xroot(10,15,:)
...
ans(:,:,363) =
0
ans(:,:,364) =
0
ans(:,:,365) =
33.0133
ans(:,:,366) =
84.2195
ans(:,:,367) =
0
etc...
I want to extract the 2 needed values and Xroot to be (10x33x2).
Notes:
[some of Xroot(z,w) contains fully of zeros, as that means there is no solution at that z,w] so, in this case i want them to be two zeros as Xroot (10x33x2).
[Note that, not all Xroot(:,:,1:2) are the needed values, they are can be Xroot(:,:,365:366) like Xroot(10,15,:), but there are always come Consecutivly ]
Réponse acceptée
Plus de réponses (2)
% Xroot(z,w,k) (10x33x402).
m1 = 10; m2 = 33; m3 = 402;
m1 = 4; m2 = 5; m3 = 6;
% Generate data
Xroot = zeros(m1, m2, m3);
for i=1:m1
for j=1:m2
Xroot(i, j, randperm(m3, 2)) = rand(1,2); % 2 nonzeros
end
end
% Get the index
idx = zeros(m1, m2, 2);
val = zeros(m1, m2, 2);
for i=1:m1
for j=1:m2
[v1, i1] = sort(Xroot(i,j,:), 'descend');
idx(i,j,:) = i1(1:2);
val(i,j,:) = v1(1:2);
fprintf('i=%3d j=%3d idx: %3d %3d; val: %f %f\n', i, j, idx(i,j,:), val(i,j,:));
end
end
1 commentaire
Anas Zh
le 7 Juil 2022
Assuming that each dim3 vector contains either 2 or 0 nonzero elements:
% an example array
A = cat(3,[0 0 0; 0 1 0; 5 0 0], ...
[0 3 0; 0 2 0; 6 0 0], ...
[0 4 0; 0 0 0; 0 0 0])
% get nonzero elements, rearrange
Ar = nonzeros(permute(A,[3 1 2]));
Ar = reshape(Ar,2,[]).'
% construct output array
hasroots = repmat(any(A,3),1,1,2);
B = zeros([size(A,1) size(A,2) 2]);
B(hasroots) = Ar
There are probably other ways as well.
Catégories
En savoir plus sur Mathematics dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!