Clear Filters
Clear Filters

How can I sort strings using only a piece of them?

8 views (last 30 days)
I have an array of strings in the format 'text#_text#. I want Matlab to be able to recognize the numbers in the strings so I can rearrange them in whichever order I decide. How can I go about doing this? # is any random whole number
Example:
A = (e12_u1, e3_u1, e3_u2, e13_u1)
B = (e6_u1, e4,u1, e4_u2, e13_u1)
No matter if I give A or B, I want the program to be able to recognize the numbers and order them, for example, in the following way:
(e12, e11, e9, e4, e3, e8, e1, e10, e2, e5, e6, e7) and place a zero if the number is not there.

Answers (1)

Guillaume
Guillaume on 30 Jan 2018
Note: when giving examples it really helps if you use valid matlab syntax so
  • we can just copy/paste your example into matlab without having to type anything
  • there's no ambiguity on the type of input and output
  • we don't have to guess what place a 0 in (e12, e11, e9, e4, e3, e8, e1, e10, e2, e5, e6, e7) actually mean. (I've no idea there!)
A = {'e12_u1', 'e3_u1', 'zz7_g4'}
number = str2double(regexp(A, '\d+', 'match', 'once')); %the regexp extract the first string of digits from each char array.
[~, order] = sort(number, 'desc');
A(order)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!