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

时间:2013-03-08 07:16:45

标签: 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=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将根据代码而有所不同,并且不固定。用于生成结果的代码可在此处查看:Need help debugging this code in Matlab


如果您需要更多相关信息,请与我们联系。

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

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);