How to remove repeating characters in a character array?

For example, I have a 4 x 2 char array, moviecountry. It looks like this, ['US'; 'FR'; 'US'; 'CA']. I would like to have another character array, states, that only stores the non-repeating elements of this array, so in this case, states = ['US'; 'FR'; 'CA']. I have the following code right now:
states = [];
for jj = 1:size(moviecountry,1)
currentcountry = moviecountry(jj,:); %set temp country and compare with other
if jj == 1
states = [currentcountry];
end
for kk = 1:size(states,1)
if ~ismember(currentcountry, states(kk, :))
states = [states;currentcountry]%only add to output if no repetition
end
end
end

 采纳的回答

See unique.

5 个评论

Got it! I tried unique at first and thought it didn't work for char arrays. Had to convert it to a cell. Thank you so much!
cellstr() or string()
Glad I could help.
" I tried unique at first and thought it didn't work for char arrays."
It does.
"Had to convert it to a cell."
Converting to cell is not required:
M = ['US'; 'FR'; 'US'; 'CA']
M = 4×2 char array
'US' 'FR' 'US' 'CA'
unique(M,'rows','stable')
ans = 3×2 char array
'US' 'FR' 'CA'
Note Stephen's use of column vectors. If M is a row vector you won't be able to use this method.
@Adam Danz: I just copied the char array verbatim from the question: "I have a 4 x 2 char array, moviecountry. It looks like this, ['US'; 'FR'; 'US'; 'CA']."

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Data Type Conversion 的更多信息

产品

版本

R2021a

标签

Community Treasure Hunt

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

Start Hunting!

Translated by