【问题标题】:Print specific parts of a cell as strings in matlab?在matlab中将单元格的特定部分打印为字符串?
【发布时间】:2013-03-08 07:16:44
【问题描述】:

我有以下矩阵数组 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


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

【问题讨论】:

    标签: arrays string matlab cell printf


    【解决方案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
    

    此代码的简短说明(根据 cmets 的要求)如下。为了简单起见,示例仅限于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);
    

    【讨论】:

    • 像魅力一样工作,谢谢!你能解释一下代码是如何工作的吗?想学习:)
    猜你喜欢
    • 2021-02-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2014-05-25
    • 2019-08-18
    • 1970-01-01
    相关资源
    最近更新 更多