How to delete a Matrix in a 3D Matrix?
9 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Karoline Peters
il 18 Mag 2022
Risposto: Steven Lord
il 19 Mag 2022
Hello,
I would like to delete a Matrix in my 3D Matrix if one element in that Matrix is NaN.
Size of T5 = 4x4x30
For example if Matrix 4x4x1 looks like this:
val(:,:,1) =
NaN NaN NaN NaN
NaN NaN NaN NaN
NaN NaN NaN NaN
0 0 0 1
I want to delete the whole Matrix.
My code does not work
[a b c] = size(T5)
for i = i:c
if isnan(T5(:,:,i))
T5(:,:,i) = [];
end
end
What am I doing wrong?
1 Commento
dpb
il 18 Mag 2022
Modificato: dpb
il 19 Mag 2022
if any(isnan(T5(:,:,i)))
...
See the doc on explanation of how logical if works for arrays -- in short it returns true only if all elements are true.
You can do the above w/o any looping in MATLAB with logical addressing---
ip=find(isnan(x)); % the linear indices in x containing NaN
if ~isempty(ip)
[~,~,ip]=ind2sub(size(x),ip); % any plane with at least one NaN
x(:,:,unique(ip))=[]; % remove those planes
end
Risposta accettata
David Hill
il 18 Mag 2022
idx=[];
for k=1:size(T5,3)
if any(isnan(T5(:,:,k)),'all')
idx=[idx,k];
end
end
T5(:,:,idx)=[];
0 Commenti
Più risposte (2)
Sulaymon Eshkabilov
il 18 Mag 2022
You are trying to change the size of the matrix that can't be achieved in this way. If you need to find and substitute NaNs with some values, then it is much better to use this approach, e.g.:
clear A
A(:,:,1) = randi([-2, 2], 5);
A(:,:,2) = randi([-2, 2], 5);
A(:,:,3) = randi([-2, 2], 5);
A=A/0;
disp(A)
%
[R C L] = size(A)
for ii = 1:L
for jj = 1:R
for kk = 1:C
if isnan(A(jj,kk,ii))
A(jj,kk,ii) = 0;
else
A(jj,kk,ii) = 13;
end
end
end
end
disp(A)
1 Commento
dpb
il 18 Mag 2022
"... trying to change the size of the matrix that can't be achieved in this way..."
Certainly can delete a plane by setting it's values to [] by logical addressing.
The problem is with the tes, not the replacementt; it only will be true if all elements of the plane are NaN so that part of the code is never executed with the sample data.
Steven Lord
il 19 Mag 2022
Let's make a sample 3-D array with some NaN values.
A = randi(10, 3, 3, 4);
A(randperm(numel(A), 3)) = NaN % Make 3 random values NaN
Identify the pages that contain NaN.
nanpages = any(isnan(A), [1 2]) % Compute any over dimensions 1 and 2
Now delete.
A(:, :, nanpages) = []
0 Commenti
Vedere anche
Categorie
Scopri di più su Data Type Identification in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!