Deleting a substring
I am trying to write a program that removes the index of a cell array if it contains a specific string.
For example, if the input to a function is equal ({'Hello how are you?', 'I'm fine thank you', 'Have a nice day!'}, 'you')
, only a string is returned 'Have a nice day!'
.
This is what I have so far (it does not remove the index, only the instances where it occurs):
function d = take_out(v, s)
d = regexprep(v(:), s, '');
end
source to share
Try the following:
function d = take_out(v, s)
d = v(cellfun('isempty', regexp(v(:), s)));
end
regexp(v(:), s)
returns for each cell v
(possibly empty) a vector with integer indices of each occurrence s
. cellfun('isempty', ...)
checks if these vectors are empty and returns a boolean index that is used to select the corresponding cells v
.
source to share