Remove specific entry in a cell array

199 ビュー (過去 30 日間)
ZigzS
ZigzS 2018 年 1 月 31 日
コメント済み: Jan 2022 年 10 月 11 日
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

採用された回答

James Tursa
James Tursa 2018 年 1 月 31 日
animals(ismember(animals,'dog')) = [];
  2 件のコメント
Nischal Amin
Nischal Amin 2022 年 10 月 10 日
This does not work for me.
X = ('Cat', 'Dog', 'Tiger');
X = X(ismember(X,'Tiger')) == []
X should be 'Cat', 'Dog', Empty cell
Basically, I don't want the X index to change. I just want to remove Tiger. So, when I do unique(X)...it displays only Cat and Dog.
Jan
Jan 2022 年 10 月 11 日
X = ('Cat', 'Dog', 'Tiger') is no valid Matlab syntax. For a cell array you need curly braces, not parentheses.
X(ismember(X,'Tiger')) == [] compares the cell {'Tiger'} with the empty matrix. It does not set anything to the empty cell.
X = {'Cat', 'Dog', 'Tiger'};
X(ismember(X,'Tiger')) = {''}
X = 1×3 cell array
{'Cat'} {'Dog'} {0×0 char}
% Or faster:
X = {'Cat', 'Dog', 'Tiger'};
X(strcmp(X, 'Tiger')) = {''}
X = 1×3 cell array
{'Cat'} {'Dog'} {0×0 char}

サインインしてコメントする。

その他の回答 (2 件)

Akira Agata
Akira Agata 2018 年 1 月 31 日
Another way to do it:
idx = strcmp(animals,'dog');
animals(idx) = [];
  1 件のコメント
Jan
Jan 2018 年 1 月 31 日
If only one string has to be removed, this is the fastest solution. +1

サインインしてコメントする。


Jan
Jan 2018 年 1 月 31 日
animals = {'cat', 'dog', 'mouse', 'horse'};
animals = setdiff(animals, {'dog'})
This would allow to remove multiple elements at once.
  7 件のコメント
RITESH KUMAR
RITESH KUMAR 2019 年 9 月 18 日
can we write element number at place of dog. it is at 2nd place. can i write 2.
Arpit Agarwal
Arpit Agarwal 2020 年 1 月 9 日
cool

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by