find unique words in a 54x1 cell array

I have a cell array of the states used in a data collection. Some of the states are used more than once. I need to find how mant unique states were used in the collection. I have tried to use unique but the I can't seem to get it to work due to the cells being letters not numerical characters.

Answers (1)

states = {'red', 'yellow', 'green', 'blue', 'cyan', 'blue', 'yellow', 'green', 'orange'}
states = 1×9 cell array
{'red'} {'yellow'} {'green'} {'blue'} {'cyan'} {'blue'} {'yellow'} {'green'} {'orange'}
unique(states)
ans = 1×6 cell array
{'blue'} {'cyan'} {'green'} {'orange'} {'red'} {'yellow'}
length(ans)
ans = 6

6 Comments

So the data was extracted from a Excel graph and is a 54 line column. Unique(states) doesnt work because they are not a string? I don't know how to transform a 54 line column into the form you wrote.
{'red', 'yellow'} and so on is not a string, it is a cell array of character vectors. You can do the same thing with string objects, though.
states = string({'red', 'yellow', 'green', 'blue', 'cyan', 'blue', 'yellow', 'green', 'orange'})
states = 1×9 string array
"red" "yellow" "green" "blue" "cyan" "blue" "yellow" "green" "orange"
unique(states)
ans = 1×6 string array
"blue" "cyan" "green" "orange" "red" "yellow"
length(ans)
ans = 6
Is it possible that you have a cell array of numeric scalar values? If so then use cell2mat() to convert into a numeric array that you can then unique()
I got an error
CELL2MAT does not support cell arrays containing cell arrays or objects.
When I copy the "states" file it is written as ["AL"; "AZ";...etc... "WY"]
Is there a way to transform this into {'Al', 'Az', ...etc... 'WY'}?
["AL"; "AZ";...etc... "WY"]
That is not a cell array, that is a string() array, and unique() would work fine on it.
Is it possible that you have a cell array, and inside the cell array you have scalar string objects?
states = {"red", "yellow", "green", "blue", "cyan", "blue", "yellow", "green", "orange"}
states = 1×9 cell array
{["red"]} {["yellow"]} {["green"]} {["blue"]} {["cyan"]} {["blue"]} {["yellow"]} {["green"]} {["orange"]}
unique(vertcat(states{:}))
ans = 6×1 string array
"blue" "cyan" "green" "orange" "red" "yellow"
length(ans)
ans = 6

Sign in to comment.

Categories

Products

Asked:

on 1 Apr 2022

Commented:

on 3 Apr 2022

Community Treasure Hunt

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

Start Hunting!