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

5 ビュー (過去 30 日間)
Keanu Guardiola Flores
Keanu Guardiola Flores 2018 年 1 月 30 日
編集済み: Walter Roberson 2018 年 1 月 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 Center および File ExchangeData Type Identification についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by