How to delete a Matrix in a 3D Matrix?
조회 수: 11 (최근 30일)
이전 댓글 표시
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
dpb
2022년 5월 18일
편집: dpb
2022년 5월 19일
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
채택된 답변
David Hill
2022년 5월 18일
idx=[];
for k=1:size(T5,3)
if any(isnan(T5(:,:,k)),'all')
idx=[idx,k];
end
end
T5(:,:,idx)=[];
댓글 수: 0
추가 답변 (2개)
Sulaymon Eshkabilov
2022년 5월 18일
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
dpb
2022년 5월 18일
"... 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
2022년 5월 19일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!