I'm trying to sort a string of letters into repetition of each letter.
for example:
Text= 'KKKKLLOOKkl';
Result should be {'4K','2L','2O','1K,'1k','1l'}
  1. Text could be any length.
  2. Text could be only alphabet letters (capital and small).
  3. Result could be any type of array (vector/ table/ cell ect).
I used 'unique' to get which letters are inside Text but how do I count the repetition for each occurence?
Is there a fast way or a function instead of looping for each result of unique?
Text = 'KKKKLLOOKkl';
[C,~,Xz] = unique(Text,'stable')
C = 'KLOkl'
Xz = 1,1,1,1,2,2,3,3,1,4,5
Thanks for any help :)

 採用された回答

Voss
Voss 2022 年 2 月 12 日

0 投票

Text = 'KKKKLLOOKkl';
[C,~,Xz] = unique(Text,'stable');
idx = [true; diff(Xz) ~= 0];
strcat(sprintfc('%d',diff([find(idx); numel(Text)+1])),C(Xz(idx)).').'
ans = 1×6 cell array
{'4K'} {'2L'} {'2O'} {'1K'} {'1k'} {'1l'}

2 件のコメント

Lex Luthor
Lex Luthor 2022 年 2 月 12 日
Looks great! better then what I had..
Thank you!
Voss
Voss 2022 年 2 月 12 日
Excellent!

サインインしてコメントする。

その他の回答 (1 件)

Stephen23
Stephen23 2022 年 2 月 13 日

1 投票

T = 'KKKKLLOOKkl';
D = [true,diff(T)~=0];
L = diff(find([D,true]));
C = compose('%s%d',T(D).',L(:))
C = 6×1 cell array
{'K4'} {'L2'} {'O2'} {'K1'} {'k1'} {'l1'}

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

質問済み:

2022 年 2 月 12 日

回答済み:

2022 年 2 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by