gpt4 book ai didi

string - 如何在 MATLAB 中构造 "excel-friendly"字符串?

转载 作者:行者123 更新时间:2023-12-03 03:48:56 26 4
gpt4 key购买 nike

我想构建一个表如下:

Feature  |   F-score   |   Precision  |   Recall    |
Feature1 | 0.81 (0.82) | 0.83 (0.84) | 0.85 (0.86) |
Feature2 | 0.87 (0.88) | 0.83 (0.84) | 0.85 (0.86) |
.. etc

(|字符仅代表一个新列,在字符串中不是必需的)

我只需要构造“内部”部分,即仅以数字作为字符串的部分并将其复制到剪贴板,这样我就可以转到 Excel 并立即粘贴整个内容。这可能吗?如果是这样,我将不胜感激一个有效的例子。

到目前为止我尝试过的:

我尝试按如下方式构造字符串:

str = [num2str(fscore1,2) ' (' num2str(fscore2,2) ')\t etc'];

显然'\t'不符合我的目的。我也不知道如何自动将字符串复制到剪贴板。因此,任何帮助将不胜感激。

最佳答案

您想要做的主要问题是简单的字符串连接(使用 []strcat)处理 \t作为字符串文字(字符 \ 后跟字符 t)而不是控制序列。相反,您需要使用 sprintffprintfchar(9)(9 是制表符的 ASCII)来包含制表符。

% The way that you tried
['a\t', 'b'];
% 'a\tb'

% The way that it should be
sprintf('a\tb')
% a b

% Or using char(9)
['a', char(9), 'b']
% a b

对于“Excel 友好”字符串,您希望在行中的值之间使用一些分隔符(可能制表符是最简单的),然后在行之间使用换行符。我们可以使用 sprintf 轻松构造这样的字符串(请参阅下面的代码片段)。

就自动将某些内容复制到剪贴板而言,内置 clipboard函数允许您将字符串复制到系统剪贴板。您可以根据数据构建制表符分隔的字符串并将其存储在剪贴板中。然后您可以将其粘贴到 Excel(或任何程序)中。

您需要构建与此类似的字符串:

% Labels for the columns
header = sprintf('%s\t', 'Feature', 'F-score', 'Precision', 'Recall');

% Store your data within a cell array
data = {'Feature1', 0.81, 0.82, 0.83, 0.84, 0.85, 0.86;
'Feature2', 0.87, 0.88, 0.83, 0.84, 0.85, 0.86}.';

% Construct your tab-delimited string with newlines between rows
datastring = sprintf('%s\t%0.2f (%0.2f)\t%0.2f (%0.2f)\t%0.2f (%0.2f)\n', data{:});

% Append the header to the rest of the data
fullstring = sprintf('%s\n%s', header, datastring);

% Copy this string to the system clipboard
clipboard('copy', fullstring);

您可以将结果粘贴到 Excel(或相关程序)中以生成如下所示的结果:

enter image description here

另一个选项是将数据放入元胞数组中,您可以使用工作区变量编辑器对其进行可视化。从工作区查看器中,您可以复制内容(就像在 Excel 中一样)并将其粘贴到任何程序中。

关于string - 如何在 MATLAB 中构造 "excel-friendly"字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37597262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com