3

I have a cell array (10001x21) in which the first 3 columns have data in all the rows. From columns 4 to 21 I have data In some of the cells of a particular row and some rows might be completely empty.

I want to retain only rows which have the data in some of the columns from 4 to 21 and remove all the empty rows which do not have any data in the columns (4:21). Any help would be appreciated in this case.Thanks.

This is in Matlab environment

This is how the data looks

'1Fb6' 2014 'F' [] [] [] [] [] [] [] [] [] []
'1Fc6' 2014 'F' [] [] [] [] [] [] [] [] [] []
'1Fd6' 2014 'F' [] [] [] [] [] 'ka1' [] [] [] []
'1Fk6' 2014 'F' [] [] [] [] [] [] [] [] [] []
'1Fy6' 2014 'F' [] [] [] [] [] [] [] [] [] []
'1Fz6' 2014 'F' [] [] 'na1' [] [] [] [] [] [] []
'1Fj6' 2014 'F' [] [] [] [] [] [] [] [] [] []
'1Fm6' 2014 'F' [] [] [] [] [] [] [] [] [] []
'1Fn6' 2014 'F' [] [] [] [] 'bo1' [] [] [] [] []

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
calib_san
  • 101
  • 1
  • 6

1 Answers1

2

Let's assume that your cell array was called data, with dimensions [rows, columns]. You can retain only all rows that have some data in columns 4:21 in a new matrix called new_data using this code:

new_data = data(~all(cellfun('isempty', data(:, 4:21)), 2), :);

To break this down:

  • cellfun('isempty', data(:, 4:21)) returns a matrix of size [rows, columns-3]. Any empty cells in data from columns 4:21 are labeled 1, and all other cells are labeled 0.
  • ~all(cellfun(...), 2) returns a vector of size rows x 1. It takes this previous matrix and sees if each row is a cell array of all 1's (in other words, if this row is completely empty). The all function returns true if the row is all 1's. However, because of the NOT operator (~), all rows with only 1's are actually labeled 0, and all other rows are labeled 1. In other words, the rows labeled 1 are the rows that we wish to keep.
  • new_data = data(all(...), :) simply returns the data matrix, deleting any rows that are completely empty in columns 4:21.
needarubberduck
  • 596
  • 3
  • 17
  • You can [remove that `find`](http://blogs.mathworks.com/steve/2008/01/28/logical-indexing/). Also, `'isempty'` [may be](http://www.mathworks.com/matlabcentral/answers/42335-array-cellfun-vs-for-loop) [faster](http://stackoverflow.com/questions/16143314/matlab-arrayfun-cellfun-spfun-and-structfun-vs-simple-for-loop) than `@isempty` – Luis Mendo Aug 04 '15 at 23:43
  • @Luis Mendo Thank you for mentioning these tips. Edited my answer. – needarubberduck Aug 05 '15 at 00:53
  • @It's Magic - This worked .Thanks a lot.i tried doing this before dtc_final_1(all(cellfun(@isempty,dtc_final_1(,4:21)),2),:)=[].This was not doing the job. – calib_san Aug 05 '15 at 11:33