How to delete a Matrix in a 3D Matrix?
13 ビュー (過去 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!