Ralph
Ralph

Reputation: 19

Group characters and form a matrix in Matlab

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 yz

My Matlab coding is as follows:

str = 'abcdefghijklmnopqrstuvwxyz';

fstr = [repmat('%c', 1, 4) ' '];

A=fprintf(fstr, str);

Problem: I wish to make it a new line when there are 8 characters in a row which is like this:

abcd efgh
ijkl mnop
qrst uvwx
yz

Any ideas to do this? Please help.

Thank you.

Upvotes: 0

Views: 110

Answers (3)

Divakar
Divakar

Reputation: 221614

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       

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112749

Another approach using regular expressions:

str = 'abcdefghijklmnopqrstuvwxyz';
str = regexprep(str, '(.{4})', '$1 ');
str = regexprep(str, '(.{4} .{4}) ', '$1\n');

Upvotes: 0

chengvt
chengvt

Reputation: 553

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)

Upvotes: 0

Related Questions