代码之家  ›  专栏  ›  技术社区  ›  danatel

如何在matlab中同时显示字符串和数字?

  •  2
  • danatel  · 技术社区  · 15 年前

    我有一个 500比1 字符串矩阵 S 和A 500比1 数字矩阵 N . 我想在变量编辑器中看到它们,如下所示:

    S(1) N(1)
    S(2) N(2)
    ...
    S(500) N(500)
    

    这有可能吗?

    2 回复  |  直到 15 年前
        1
  •  3
  •   Andrew Janke    15 年前

    狭隘地说你的问题,只是把数字转换成单元格。您将拥有一个数组编辑器可以处理的变量。

    X = [ S num2cell(N) ];
    

    更广泛地说,这里有一个面向数组的sprintf变体,它对于显示由并行数组构造的记录很有用。你可以这样称呼它。我经常用这种方法显示表格数据。

    sprintf2('%-*s  %8g', max(cellfun('prodofsize',S)), S, N)
    

    功能如下。

    function out = sprintf2(fmt, varargin)
    %SPRINTF2 Quasi-"vectorized" sprintf
    %
    % out = sprintf2(fmt, varargin)
    %
    % Like sprintf, but takes arrays of arguments and returns cellstr. This
    % lets you do formatted output on nonscalar arrays.
    %
    % Example:
    % food = {'wine','cheese','fancy bread'};
    % price = [10 6.38 8.5];
    % sprintf2('%-12s %6.2f', food, price)
    % % Fancier formatting with width detection
    % sprintf2('%-*s %6.2f', max(cellfun('prodofsize',food)), food, price)
    
    [args,n] = promote(varargin);
    out = cell(n,1);
    for i = 1:n
        argsi = grab(args, i);
        out{i} = sprintf(fmt, argsi{:});
    end
    
    % Convenience HACK for display to command line
    if nargout == 0
        disp(char(out));
        clear out;
    end
    
    function [args,n] = promote(args)
    %PROMOTE Munge inputs to get cellstrs
    for i = 1:numel(args)
        if ischar(args{i})
            args{i} = cellstr(args{i});
        end
    end
    n = cellfun('prodofsize', args);
    if numel(unique(n(n > 1))) > 1
        error('Inconsistent lengths in nonscalar inputs');
    end
    n = max(n);
    
    function out = grab(args, k)
    %GRAB Get the kth element of each arg, popping out cells
    for i = 1:numel(args)
        if isscalar(args{i})
            % "Scalar expansion" case
            if iscell(args{i})
                out{i} = args{i}{1};
            else
                out{i} = args{i};
            end
        else
            % General case - kth element of array
            if iscell(args{i})
                out{i} = args{i}{k};
            else
                out{i} = args{i}(k);
            end
        end
    end
    
        2
  •  5
  •   gnovice    15 年前

    下面将允许您在命令窗口中一起查看变量:

    disp([char(S) blanks(numel(N))' num2str(N)]);
    

    数组 S (我假定是一个单元格数组)使用函数转换为字符数组 CHAR . 然后将其与一列空白向量连接(使用函数 BLANKS )然后是数字数组的字符串表示形式 N (使用函数生成 NUM2STR )然后使用功能显示 DISP .