0

I have a MATLAB array of structs with a field called image_name. There are a few entries where

x(n).image_name = []

(i.e., the nth row of the struct array has an image_name that's empty)

I would like to remove them by trying something along the lines of

idx = [x.image_name] == []
x(idx) = [];

but can't get the indices of the empty strings. Every variation I try generates an error.

How can I find the row indices of the empty strings, so I can remove them?

Suever
  • 64,497
  • 14
  • 82
  • 101
user1245262
  • 6,968
  • 8
  • 50
  • 77

1 Answers1

5

You can use {} to convert the names to a cell array and then use isempty (within cellfun) to find the empty entries and remove them.

ismt = cellfun(@isempty,  {x.image_name});
x = x(~ismt);

Or in one line

x = x(~cellfun(@isempty, {x.image_name}));

Update

As mentioned by @Rody in the comments, using 'isempty' rather than constructing an anonymous function is significantly faster.

x = x(~cellfun('isempty', {x.image_name}));
Community
  • 1
  • 1
Suever
  • 64,497
  • 14
  • 82
  • 101
  • 4
    +1. Just for completeness: using the string argument to `cellfun` used to be a lot faster than using anonymous functions (i.e., `cellfun('isempty', {x.image_name})`). Not sure if this is still true in recent MATLAB... – Rody Oldenhuis May 02 '16 at 16:40
  • @RodyOldenhuis Oh wow, just tested it and it looks like it's still true. I never realized that, thanks! – Suever May 02 '16 at 16:42
  • Good to know it still works :) Be sure to check out the other possible string arguments; old-fashioned, but pretty darned useful for larger cell arrays. – Rody Oldenhuis May 02 '16 at 16:44
  • This is interesting. I thought that difference between `@isempty` and `'isempty'` would have disappeared in recent versions. Which version did you test on, @Suever? – Luis Mendo May 02 '16 at 23:31
  • @LuisMendo Tested on R2015b (new execution engine). Used the following script: `a = {'a', ''}; b = a(randi(1:2,1000,1)); disp(timeit(@()cellfun(@isempty, b))); disp(timeit(@()cellfun('isempty', b)));` – Suever May 02 '16 at 23:35
  • @Suever Thanks. I also get faster results (about 70 times) with R2015b on Windows 7 – Luis Mendo May 02 '16 at 23:37