查看单个帖子
旧 2019-12-10, 16:49   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 如何在MATLAB中一起显示字符串和数字?

我有字符串的500×1矩阵S和数量的500×1矩阵N 。我想像这样在变量编辑器中一起看到它们:

S(1) N(1) S(2) N(2) ... S(500) N(500) 这可能吗?


回答:
简而言之,只需将数字转换为单元格即可。您将拥有数组编辑器可以处理的单个变量。

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

更多&回答...
poster 当前离线   回复时引用此帖