Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 在Matlab中对字符进行分组并形成矩阵_Arrays_Matlab_Matrix - Fatal编程技术网

Arrays 在Matlab中对字符进行分组并形成矩阵

Arrays 在Matlab中对字符进行分组并形成矩阵,arrays,matlab,matrix,Arrays,Matlab,Matrix,我有26个字符A到Z,我将4个字符组合在一起,并用空格分隔以下4个字符,如下所示: abcd efgh ijkl mnop qrst uvwx yz abcd efgh ijkl mnop qrst uvwx yz 我的Matlab编码如下: str='abcdefghijklmnopqrstuvwxyz' fstr=[repmat('%c',1,4') A=fprintf(fstr,str) 问题:当一行中有8个字符时,我希望将其设为新行,如下所示: abcd efgh ijkl mnop

我有26个字符A到Z,我将4个字符组合在一起,并用空格分隔以下4个字符,如下所示:

abcd efgh ijkl mnop qrst uvwx yz
abcd efgh
ijkl mnop
qrst uvwx
yz
我的Matlab编码如下:

str='abcdefghijklmnopqrstuvwxyz'

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

A=fprintf(fstr,str)

问题:当一行中有8个字符时,我希望将其设为新行,如下所示:

abcd efgh ijkl mnop qrst uvwx yz
abcd efgh
ijkl mnop
qrst uvwx
yz
有什么办法吗?请帮忙

谢谢。

代码(一种方法)-

%// 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)
>> input_str
input_str =
abcdefghijklmnopqrstuvwxyz
>> output_str
output_str =
abcd efgh 
ijkl mnop 
qrst uvwx 
yz       
代码运行-

%// 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)
>> input_str
input_str =
abcdefghijklmnopqrstuvwxyz
>> output_str
output_str =
abcd efgh 
ijkl mnop 
qrst uvwx 
yz       

另一种方法是使用
regexp

A='abcd efgh ijkl mnop qrst uvwx yz';
A_splited=regexp(A, '\S\S\S\S\s\S\S\S\S', 'match')
但是,在这种情况下,最后一个“yz”不会出现。因此,需要使用类似的方法进行调整

A_splited{1,end+1}=A(end-rem(length(A),10)+1:end)

使用正则表达式的另一种方法:

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

嗨,迪瓦卡,这正是我想要的。太神了您的编码简短。非常感谢你的帮助。嗨@Divakar,我想知道为什么方法1不起作用。正如我刚才提到的,我有一个class='abcd efgh ijkl mnop qrst uvwx yz'。既然我的输入与urs相同,为什么没有输出。
A
就是
32
。你需要先解决这个问题。好的@Divakar,我知道了,谢谢:-)如果你“知道”了,为什么不编辑这个问题。目前,这只会让未来的读者感到困惑,因为你声称
A
str
在每4个字符后加空格,而这不是你问题中的代码所做的。