【问题标题】:How to extract a string from a table cell in matlab如何从matlab中的表格单元格中提取字符串
【发布时间】:2018-07-15 22:51:04
【问题描述】:

我在 Matlab 中导入了一个 csv 文件 data_tr

1, abc
2, def
...

现在打算在我的代码中使用字符串

save_location = strcat('trial\tr_',data_tr(i,2),'.png');

这导致了以下错误:

输入必须是字符向量、字符向量元胞数组或字符串数​​组。

变量 data_tr(i,2) 被认为是一个 1x1 表而不是字符串。

看了一些答案(this一),我也试过这个:

da = data_tr(i,2);
h = [da{:}];
save_location = strcat('trial\tr_',h,'.png');

但这显示了一个下标错误:

使用 main 时出错(第 14 行(即第 h=[da{:}];) 行)

您不能使用线性索引(一个下标)或多维索引(三个或更多 下标)。使用行下标和变量下标。

谁能帮我从 csv 文件中提取字符串。

【问题讨论】:

  • 你试过documentation tells you和使用save_location=strcat('trial\tr_',data_tr{i,2},'.png');吗?
  • 是的,我使用了 help strcat。它将字符串作为输入。此外strcat(int2str(28),'trial.png') 工作正常。问题是 da=data_tr(i,2); 被 matlab 视为 1x1 表(显示在 var 部分),我不知道如何从中提取字符串。
  • 您可以尝试使用data_tr.Var2{i,1}。该表将自动将Var1Var2 等分配为表中的变量名,因此您的第二列应为Var2
  • 那行得通。我去了导入数据部分,在导入时,将列重命名为 col_1 和 col_2。 data_tr.col_1(i) 是正确的语法。非常感谢! 已解决
  • 请实际阅读我链接的文档。 (){} 是有区别的。

标签: string matlab csv cell


【解决方案1】:

听起来您正在使用某些导入工具(例如this)手动加载数据。改用loading the data programmatically,您可能会让事情变得更轻松。这将使您可以根据您正在使用的特定文件格式定制数据加载,并对数据格式进行更多控制。

例如,对于给定的示例文件,您可以使用xlsread

[~, strData] = xlsread('data_tr.csv');  % Load string data into a cell array
strData = strtrim(strData);             % Remove leading or trailing blanks
...
save_location = strcat('trial\tr_', strData{i}, '.png');  % Access a string

或者你可以使用textscan:

fid = fopen('data_tr.csv', 'r');               % Open file for reading
C = textscan(fid, '%*d%s', 'Delimiter', ',');  % Read just the strings
fclose(fid);                                   % Close file
strData = C{1};                                % Remove cell encapsulation
...
% Use the same way as above

【讨论】:

  • 我使用 csvread 获取数据,但要重命名列,我手动导入了表。无论如何,它会创建相同的 300x2 表,我不知道使用 花括号 来访问字符串。虽然感谢您的建议!
【解决方案2】:

使用花括号访问表格元素

data_tr{i,2} % Get the element of a table rather than data_tr(I,2)

或者将其转换为单元格,因为strcat 可以接受单元格输入

data_tr_cell = table2cell(data_tr);
data_tr_cell(i, 2);

【讨论】:

  • 谢谢!我也不知道。后一种方法更有用,因为 **strcat ** 的输出也是单元格。
猜你喜欢
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 2015-03-18
  • 2011-01-22
  • 1970-01-01
  • 2019-05-24
相关资源
最近更新 更多