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?
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}));