How to remove NaNs from rows in matrices within a cell array?
4 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
the cyclist
on 30 Jan 2022
Edited: the cyclist
on 30 Jan 2022
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 Comments
the cyclist
on 31 Jan 2022
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),:)
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!