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

11 次查看(过去 30 天)
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.

回答(1 个)

Guillaume
Guillaume 2018-1-30
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)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by