Group characters and form a matrix in Matlab

后端 未结 3 1334
太阳男子
太阳男子 2021-01-27 12:02

I have 26 characters A to Z, I group 4 characters together and separate the following 4 characters by a space which is like this:

abcd efgh ijkl mnop qrst uvwx y         


        
相关标签:
3条回答
  • 2021-01-27 12:15

    Another approach using regular expressions:

    str = 'abcdefghijklmnopqrstuvwxyz';
    str = regexprep(str, '(.{4})', '$1 ');
    str = regexprep(str, '(.{4} .{4}) ', '$1\n');
    
    0 讨论(0)
  • 2021-01-27 12:34

    Code ( an approach with vec2mat) -

    %// Input
    input_str = 'abcdefghijklmnopqrstuvwxyz' %// Input
    
    %// Parameters
    group_numel = 4;
    num_groups_per_row = 2;
    
    str1 = vec2mat(input_str,group_numel)
    str2 = [str1,repmat(' ',size(str1,1),1)]
    output_str = vec2mat(str2,(group_numel+1)*num_groups_per_row)
    

    Code run -

    >> input_str
    input_str =
    abcdefghijklmnopqrstuvwxyz
    >> output_str
    output_str =
    abcd efgh 
    ijkl mnop 
    qrst uvwx 
    yz       
    
    0 讨论(0)
  • 2021-01-27 12:37

    Another method is to use regexp

    A='abcd efgh ijkl mnop qrst uvwx yz';
    A_splited=regexp(A, '\S\S\S\S\s\S\S\S\S', 'match')
    

    However, the last 'yz' will not appear in this case. So there will be a need to tweak using something like this.

    A_splited{1,end+1}=A(end-rem(length(A),10)+1:end)
    
    0 讨论(0)
提交回复
热议问题