Superbest
Superbest

Reputation: 26622

Sort a cell array of strings alphabetically by last name

In Matlab, I have a cell array like:

names = {
    'John Doe',
    'Jane Watkins',
    'Jeremy Jason Taylor',
    'Roger Adrian'
    }

I would like to sort these such that the last names appear in alphabetical order. In my example, it would come out being:

names_sorted = {
    'Roger Adrian',
    'John Doe',
    'Jeremy Jason Taylor',
    'Jane Watkins'
    }

I know of inelegant ways of doing this. For instance, I could tokenize at space, make a separate last_names cell array, sort that, and apply the indexing to my original array.

My question is, is there a better way?

Because someone is sure to come up with that list of assumptions you can't make with regards to people names in a database, let me assure you that all my names are either "FIRST MIDDLE LAST" or "FIRST LAST". I checked.

Upvotes: 2

Views: 6210

Answers (1)

Jonas
Jonas

Reputation: 74940

If all first names had the same length, then you would be able to use sortrows, but in your case, that would require padding and modifying your array, anyway, so that you're better off converting it into "LAST FIRST MIDDLE" before applying sort. Fortunately, there's a simple regular expression for that:

names = {'John Doe';'Roger Adrian';'John Fitzgerald Kennedy'};
names_rearranged = regexprep(names,'(.*) (\w*)$','$2 $1')
names_rearranged = 
    'Doe John'
    'Adrian Roger'
    'Kennedy John Fitzgerald'

[names_rearranged_sorted, idx_sorted] = sort(names_rearranged);

names_sorted = names(idx_sorted)
names_sorted = 
    'Roger Adrian'
    'John Doe'
    'John Fitzgerald Kennedy'

Upvotes: 3

Related Questions