How to remove NaNs from rows in matrices within a cell array?
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi all,
I have this cell array participant _H where some of the matrices inside the cells include NaNs. When I try and remove all of the NaNs using cellfun, like so
participant_H(cellfun(@(participant_H) any(isnan(participant_H)),participant_H)) = []
I just get an empty cell array (see attachment).
Could someone kindly help?
댓글 수: 0
채택된 답변
the cyclist
2022년 1월 30일
편집: the cyclist
2022년 1월 30일
Instead of trying to set the NaN element to [], you can just select the non-NaN elements.
participant_H_no_nan = cellfun(@(x)x(not(isnan(x))),participant_H,'UniformOutput',false);
I typically find it clearer to use a different variable name (in this case x) in the anonymous function.
댓글 수: 3
the cyclist
2022년 1월 31일
The prior code looked at each vector (inside each cell), and kept only the the non-NaNs.
That doesn't do what you intended when acting on matrices. Unlike what you stated, it is not returning the first column. It is returning all the non-NaNs of the entire matrix, in one long vector.
The following code does what you intend, I believe. Using the all function, it finds the rows where all elements are non-NaN, and returns only those rows.
participant_columns2_no_nan = cellfun(@(x)x(all(not(isnan(x)),2),:),participant_columns2,'UniformOutput',false);
I feel that I am "fishing" for you here, and not "teaching you to fish". I strongly suggest that you really try to understand what both of these pieces of code are doing, and not just use it blindly.
I would suggest you just try out on a single matrix, and not worry about the cellfun complication at first. See what each piece does, and understand it.
% Define an input
A = [ 1 2 3 NaN;
4 5 6 7;
8 9 10 11;
12 13 14 NaN];
% Which elements are NaN?
isnan(A)
% Which are not NaN?
not(isnan(A))
% Rows in which all elements are not NaN
all(not(isnan(A)),2) % Read the documentation of all(), to understand the syntax
% Use the above logical index to index into A, and pull only the desired
% rows
A(all(not(isnan(A)),2),:)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!