Arrays 在matlab中将单元格的特定部分打印为字符串?

Arrays 在matlab中将单元格的特定部分打印为字符串?,arrays,string,matlab,cell,printf,Arrays,String,Matlab,Cell,Printf,我有以下矩阵数组B: B=[1 2 3; 10 20 30 ; 100 200 300 ; 500 600 800]; 通过代码将其组合,以形成值之间的可能组合。结果存储在单元格G中,以便G: G= [1;20;100;500] [0;30;0;800] [3;0;0;600] . . etc 我想根据选择的B值格式化结果: [1 2 3] = 'a=1 a=2 a=3' [10 20 30] = 'b=1 b=2 b=3' [100 200 300]= 'c=1 c=2 c=

我有以下矩阵数组B:

B=[1 2 3; 10 20 30 ; 100 200 300 ; 500 600 800];
通过代码将其组合,以形成值之间的可能组合。结果存储在单元格G中,以便G:

G=
[1;20;100;500]
[0;30;0;800]
[3;0;0;600]
.
.
etc
我想根据选择的
B
值格式化结果:

[1 2 3]      = 'a=1 a=2 a=3'
[10 20 30]   = 'b=1 b=2 b=3'
[100 200 300]= 'c=1 c=2 c=3'
[500 600 800]= 'd=1 d=2 d=3'
例如,使用提供的当前单元格中的结果:

[1;20;100;500]
[0;30;0;800]
[3;0;0;600]
应打印为

a=1 & b=2 & c=1 & d=1 
a=0 & b=3 & c=0 & d=3  % notice that 0 should be printed although not present in B
a=3 & b=0 & c=0 & d=2
请注意,单元格G将根据代码而变化,并且不是固定的。可在此处查看用于生成结果的代码:


如果您需要更多信息,请告诉我。

您可以尝试以下方法:

k = 1; % which row of G

string = sprintf('a = %d, b = %d, c = %d, d = %d',...
    max([0 find(B(1,:) == G{k}(1))]),  ...
    max([0 find(B(2,:) == G{k}(2))]),  ...
    max([0 find(B(3,:) == G{k}(3))]),  ...
    max([0 find(B(4,:) == G{k}(4))])  ...
    );
例如,对于示例数据的
k=1
,这将导致

string =

a = 1, b = 2, c = 1, d = 1
以下是对该代码的简短解释(请参见注释)。为了简单起见,该示例仅限于G的第一个值和B的第一行

% searches whether the first element in G can be found in the first row of B
% if yes, the index is returned
idx = find(B(1,:) == G{k}(1));

% if the element was not found, the function find returns an empty element. To print  
% a 0 in these cases, we perform max() as a "bogus" operation on the results of  
% find() and 0. If idx is empty, it returns 0, if idx is not empty, it returns 
% the results of find().
val = max([0 idx])

% this value val is now formatted to a string using sprintf
string = sprintf('a = %d', val);

很有魅力,谢谢!!你能解释一下代码是如何工作的吗?想学习:)