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!