Remove specific entry in a cell array
Mostrar comentarios más antiguos
I want to remove an entry in a cell array if it is equal to something specifically. Explained in this example:
animals={'cat', 'dog', 'mouse', 'horse'};
"animals" is being redefined in a loop, and if it happens to be redefined with 'dog' as an entry, I want to remove it. So I want
animals={'cat', 'mouse', 'horse'};
I don't want to replace 'dog' with a blank (''), I want to remove that entry entirely and keep the array tight (i.e. reduce the dimensions from 4x1 to 3x1 in this case).
Thanks
Respuesta aceptada
Más respuestas (2)
Akira Agata
el 31 de En. de 2018
Another way to do it:
idx = strcmp(animals,'dog');
animals(idx) = [];
1 comentario
Jan
el 31 de En. de 2018
If only one string has to be removed, this is the fastest solution. +1
Jan
el 31 de En. de 2018
animals = {'cat', 'dog', 'mouse', 'horse'};
animals = setdiff(animals, {'dog'})
This would allow to remove multiple elements at once.
7 comentarios
jaah navi
el 28 de Oct. de 2018
I tried with your command in the following code:
code:
C = partitions([5 7 8 50])
partitions = setdiff(partitions, {'5','7'}).But i am getting error.
could you please help me to remove {'5','7'}.
Jan
el 31 de Oct. de 2018
Please post the error message instead of only mentioning, that there is one. By the way, which partitions do you mean? This is not a function of the Matlab toolboxes, so we cannot know, what you are talking of. At least it looks strange, that the input of this function is numeric, and you expect the output to be a cell string.
Peter Jarosi
el 10 de Jul. de 2019
Editada: Peter Jarosi
el 10 de Jul. de 2019
setdiff() unexpectedly sorts cells. What if I dont want this side effect?
animals = {'cat', 'dog', 'mouse', 'horse'};
animals = setdiff(animals, {'dog'})
animals =
'cat' 'horse' 'mouse'
OK, I found the answer, using 'stable' option. Nice! I really appreciate your idea. Thanks!
animals = {'cat', 'dog', 'mouse', 'horse'};
animals = setdiff(animals, {'dog'}, 'stable')
animals =
'cat' 'mouse' 'horse'
Jan
el 11 de Jul. de 2019
@Peter: If you want to remove one string only:
animals = {'cat', 'dog', 'mouse', 'horse'};
animals = animals(~strcmp(animals, 'dog'))
Peter Jarosi
el 11 de Jul. de 2019
@Jan: Actually I applied your idea for removing more than one string from a cell array. (I just used your example to illustrate the problem of sorting.) In my opinion the most convenient method is yours extending with 'stable' option, if we want to remove more than one strings and keep the original order of the remaining elements.
RITESH KUMAR
el 18 de Sept. de 2019
can we write element number at place of dog. it is at 2nd place. can i write 2.
Arpit Agarwal
el 9 de En. de 2020
cool
Categorías
Más información sobre Startup and Shutdown en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!