필터 지우기
필터 지우기

advanced sorting of cell array of strings

조회 수: 13 (최근 30일)
Kilian
Kilian 2012년 7월 28일
편집: Eldhose Poulose 2020년 3월 6일
I have the following array that I sorted in descending order (natural sort using sortn.m)
files = [
'a_20_15rpm_05.txt'
'a_20_14rpm_05.txt'
'a_20_12rpm_50.txt'
'a_20_12rpm_10.txt'
'a_20_12rpm_05.txt'
'a_20_5rpm_05.txt'
'a_20_4rpm_50.txt'
'a_20_4rpm_05.txt'
'a_20_2rpm_05.txt']
Here is what I need: the elements with equal rpms (index 3, 4 and 5 as well as 7 and 8) need to be sorted in ascending order. The final array should have the following form
files = [
'a_20_15rpm_05.txt'
'a_20_14rpm_05.txt'
'a_20_12rpm_05.txt'
'a_20_12rpm_10.txt'
'a_20_12rpm_50.txt'
'a_20_5rpm_05.txt'
'a_20_4rpm_05.txt'
'a_20_4rpm_50.txt'
'a_20_2rpm_05.txt']
I'd really appreciate some help on this. Thanks a lot for your answers in advance.

답변 (3개)

Oleg Komarov
Oleg Komarov 2012년 7월 28일
Your sample input:
files = {
'a_20_15rpm_05.txt'
'a_20_14rpm_05.txt'
'a_20_12rpm_50.txt'
'a_20_12rpm_10.txt'
'a_20_12rpm_05.txt'
'a_20_5rpm_05.txt'
'a_20_4rpm_50.txt'
'a_20_4rpm_05.txt'
'a_20_2rpm_05.txt'}
% Match the second and third group of digits (it would be nice to see more elegant ways to do that)
out = regexp(files, '(a_20_|rpm_|.txt)','split');
% Convert numeric strings to numbers and "unpack"
out = cell2mat(cellfun(@(x) str2double(x(:,2:3)),out,'un',0));
% Sort
[trash,idx] = sortrows(out,[-1,2]);
files(idx)

Andrei Bobrov
Andrei Bobrov 2012년 7월 28일
k = regexp(files,'((?<=a_20_)\d*)|((?<=rpm_)\d*)','match');
[ii,ii] = sortrows(str2double(cat(1,k{:})),[-1 2]);
files(ii)
  댓글 수: 1
Eldhose Poulose
Eldhose Poulose 2020년 3월 6일
편집: Eldhose Poulose 2020년 3월 6일
This Works for me. THANK YOU Andrei.
k= regexp(allNames,'((?<=out_)\d*)|((?<=_TRUE1_))','match'); % d* is for the varying variable, for example, 1 2 3 4 5 ...so on
[~,ii]= sortrows(str2double(cat(1,k{:}))); % [-1 2] is for ascending descending try with and without this
allNames= allNames(ii);

댓글을 달려면 로그인하십시오.


Kilian
Kilian 2012년 7월 30일
thanks a lot for all your help. this worked fine.
  댓글 수: 1
Sean de Wolski
Sean de Wolski 2012년 7월 30일
Please accept the answer which you used to mark this thread closed.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by