Matlab字符串的连接
Concatenation of Matlab strings
我想制作一个 Matlab 函数,它接受两个矩阵 A 和 B(大小相同)并以某种方式组合它们以提供可在 Latex 中使用的输出 - table。
我希望输出矩阵的第一行由矩阵 A 的第一行组成,它们之间有和号 (&),并以双反斜杠结尾。
第二行应该是 B 的第一行,括号括起来,中间是 & 号。 A 和 B 的其余部分依此类推。
如果我让 A=rand(1,2)
,我可以使用 [num2str(A(1)), ' & ', num2str(A(2)),' \']
等来做到这一点。
但我希望能够为任何大小的矩阵 A 创建一个函数。我想我必须以某种方式制作单元格结构。但是怎么办?
您可以使用sprintf
,它会根据需要多次重复格式规范,直到处理完所有输入变量:
%combine both to one matrix
C=nan(size(A).*[2,1]);
C(1:2:end)=A;
C(2:2:end)=B;
%print
sprintf('%f & %f \\\n',C.')
需要转置 (.'
) 来修复排序。
这可能是一种方法 -
%// First off, make the "mixed" matrix of A and B
AB = zeros(size(A,1)*2,size(A,2));
AB(1:2:end) = A;
AB(2:2:end) = B;
%// Convert all numbers of AB to characters with ampersands separating them
AB_amp_backslash = num2str(AB,'%1d & ');
%// Remove the ending ampersands
AB_amp_backslash(:,end-1:end) = [];
%// Append the string ` \` and make a cell array for the final output
ABcat_char = strcat(AB_amp_backslash,' \');
ABcat_cell = cellstr(ABcat_char)
样本运行-
A =
183 163 116 50
161 77 107 91
150 124 56 46
B =
161 108 198 4
198 18 14 137
6 161 188 157
ABcat_cell =
'183 & 163 & 116 & 50 \'
'161 & 108 & 198 & 4 \'
'161 & 77 & 107 & 91 \'
'198 & 18 & 14 & 137 \'
'150 & 124 & 56 & 46 \'
' 6 & 161 & 188 & 157 \'
我想制作一个 Matlab 函数,它接受两个矩阵 A 和 B(大小相同)并以某种方式组合它们以提供可在 Latex 中使用的输出 - table。
我希望输出矩阵的第一行由矩阵 A 的第一行组成,它们之间有和号 (&),并以双反斜杠结尾。
第二行应该是 B 的第一行,括号括起来,中间是 & 号。 A 和 B 的其余部分依此类推。
如果我让 A=rand(1,2)
,我可以使用 [num2str(A(1)), ' & ', num2str(A(2)),' \']
等来做到这一点。
但我希望能够为任何大小的矩阵 A 创建一个函数。我想我必须以某种方式制作单元格结构。但是怎么办?
您可以使用sprintf
,它会根据需要多次重复格式规范,直到处理完所有输入变量:
%combine both to one matrix
C=nan(size(A).*[2,1]);
C(1:2:end)=A;
C(2:2:end)=B;
%print
sprintf('%f & %f \\\n',C.')
需要转置 (.'
) 来修复排序。
这可能是一种方法 -
%// First off, make the "mixed" matrix of A and B
AB = zeros(size(A,1)*2,size(A,2));
AB(1:2:end) = A;
AB(2:2:end) = B;
%// Convert all numbers of AB to characters with ampersands separating them
AB_amp_backslash = num2str(AB,'%1d & ');
%// Remove the ending ampersands
AB_amp_backslash(:,end-1:end) = [];
%// Append the string ` \` and make a cell array for the final output
ABcat_char = strcat(AB_amp_backslash,' \');
ABcat_cell = cellstr(ABcat_char)
样本运行-
A =
183 163 116 50
161 77 107 91
150 124 56 46
B =
161 108 198 4
198 18 14 137
6 161 188 157
ABcat_cell =
'183 & 163 & 116 & 50 \'
'161 & 108 & 198 & 4 \'
'161 & 77 & 107 & 91 \'
'198 & 18 & 14 & 137 \'
'150 & 124 & 56 & 46 \'
' 6 & 161 & 188 & 157 \'