I have a mixed 6x7 cell array
A = {'text' 12 NaN 14 'text' 16 17; 'text' 0 NaN 24 25 26 27; 31 32 33 34 35 0 'text'; NaN 42 43 44 45 46 0; 51 'text' 53 54 NaN 56 57; 61 62 0 64 65 NaN 67};
How do I delete the rows from 2 to 5 that have one or more cells in columns 3 to 6 equal to NaN or zero? The remaining rows should be rows 1, 4 and 6. Rows 1 and 6 should remain because, even if they have NaNs or zeros in columns 3 to 6, they should not be considered for elimination, and row 4 should remain because it does not have NaNs or zeros in columns 3 to 6. Thanks!

2 Kommentare

madhan ravi
madhan ravi am 5 Okt. 2018
Bearbeitet: madhan ravi am 5 Okt. 2018
Just can you type the desired result so that it’s easier to understand the problem?
The answer should be
B = {'text' 12 NaN 14 'text' 16 17; NaN 42 43 44 45 46 0; 61 62 0 64 65 NaN 67};

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Matt J
Matt J am 5 Okt. 2018
Bearbeitet: Matt J am 5 Okt. 2018
keep=~any( cellfun( @(c)isequal(c,0)|isequaln(c,nan) , A(:,3:6) ) , 2);
keep([1,end])=1;
B=A(keep,:)

6 Kommentare

Thanks, it does work thanks to the keep([1,end])=1 trick which adds back the rows not to be deleted. Is there a way to get the answer by only considering the rows of interest in the keep=~any... line? In other words, without deleting and then adding back the rows that should not be considered for deletion in the analysis of the array?
Matt J
Matt J am 5 Okt. 2018
Bearbeitet: Matt J am 5 Okt. 2018
Yes, you could do this instead,
keep=[true;...
~any( cellfun( @(c)isequal(c,0)|isequaln(c,nan) , A(2:end-1,3:6) ) , 2);...
true]
Wonderful! Thank you very much.
Hi Matt,
Actually, it only works in the special case I mentioned in my first question. For example, if I now want to delete the rows from 1 to 5 (rather than from 2 to 5) that have one or more cells in columns 3 to 6 equal to NaN or zero, I assume I should use:
keep=[true;...
~any( cellfun( @(c)isequal(c,0)|isequaln(c,nan) , A(1:end-1,3:6) ) , 2);...
true]
where I changed the starting row of A to be considered from 2 to 1 in your last syntax, then I get the following error:
The logical indices in position 1 contain a true value outside of the array bounds.
because the variable keep has now one more row (7) than the cell array A (6).
I am not sure why the variable keep increases in size.
Thanks
Matt J
Matt J am 5 Okt. 2018
Bearbeitet: Matt J am 5 Okt. 2018
I am not sure why the variable keep increases in size.
Because A(1:end-1,3:6) has more rows than A(2:end-1,3:6). You've given more rows to the middle part of keep but didn't take anything away.
Clear now. Thank you very much.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by