how do i rearrage words in an alphabetical order in an array?

2 vues (au cours des 30 derniers jours)
Mithushan Kanthasamy
Mithushan Kanthasamy le 15 Fév 2021
Given a list of names in an array, how do i rearrange the names in alphabetical order without any conditional functions?
names = ' john alex peter matthew'

Réponses (1)

dpb
dpb le 15 Fév 2021
names =sort( split(' john alex peter matthew' ))
names =
5×1 cell array
{0×0 char }
{'alex' }
{'john' }
{'matthew'}
{'peter' }
>>
Eliminate the zero-length element, of course.
Starting with a cellstr() or string() array would make more sense than to have them all in one char() vector.
  4 commentaires
Adam Danz
Adam Danz le 16 Fév 2021
dpb's answer works for any number of names separated by spaces. If your data are arranged differently, we're missing that information. Note that names with spaces will be parsed; example: De Franco.
sort(split('De Franco Cicero Edgars' ))
ans = 4x1 cell array
{'Cicero'} {'De' } {'Edgars'} {'Franco'}
One small thing to consider with sort() is that it's case sensitive. The two examples below are sorted incorrectly
sort(["adam", "Alan"])
ans = 1×2 string array
"Alan" "adam"
sort(["DeLuca", "Deangelo"])
ans = 1×2 string array
"DeLuca" "Deangelo"
To get around that sort with all lowercase (or uppercase) and use the index to control the final sorted order
names = ["DeLuca", "Deangelo"];
[~, idx] = sort(lower(names));
names(idx)
ans = 1×2 string array
"Deangelo" "DeLuca"
Mithushan Kanthasamy
Mithushan Kanthasamy le 16 Fév 2021
thank you! that is all i need!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by