【问题标题】:Read string from txt file and use string for loop从 txt 文件中读取字符串并使用字符串进行循环
【发布时间】:2013-08-13 17:13:58
【问题描述】:

试图读取一个 txt 文件,然后遍历该 txt 文件的所有字符串。不幸的是没有让它工作。

fid = fopen(fullfile(source_dir, '1.txt'),'r')
read_current_item_cells = textscan(fid,'%s')
read_current_item = cell2mat(read_current_item_cells);

 for i=1:length(read_current_item)

 current_stock = read_current_item(i,1); 
 current_url = sprintf('http:/www.', current_item)
 .....

我基本上尝试将单元格数组转换为矩阵,因为 textscan 输出单元格数组。但是现在我收到了消息

使用 cell2mat 时出错(第 53 行)无法支持包含元胞​​数组或对象的元胞数组。

非常感谢任何帮助

【问题讨论】:

  • 这是因为您的元胞数组 (read_current_item_cells) 中包含元胞数组。
  • 你能给出一个从 1.txt 读取的示例文本
  • 当然,这些是基本的股票代码 APPL 下一行 MSFT 等。是否需要放入分隔符?
  • stackoverflow.com/questions/13540418/… 这将帮助您可视化您的问题。
  • 谢谢,是的,我之前在寻找解决方案时发现了那个帖子,不幸的是我仍然无法修复它

标签: matlab loops


【解决方案1】:

这是textscan 的正常行为。它返回一个元胞数组,其中每个元素都是另一个元胞 OR 数组(取决于说明符),其中包含与您传递给函数的格式字符串中的每个格式说明符对应的值。例如,如果1.txt 包含

appl 12
msft 23

运行代码返回

>> read_current_item_cells
read_current_item_cells = 
    {4x1 cell}

>> read_current_item_cells{1}
ans = 
    'appl'
    '12'
    'msft'
    '23'

它本身就是另一个元胞数组:

>> iscell(read_current_item_cells{1})
ans =
     1

它的元素可以使用

>> read_current_item_cells{1}{1}
ans =
appl

现在,如果您将格式从 '%s' 更改为 '%s %d',您会得到

>> read_current_item_cells
read_current_item_cells = 
    {2x1 cell}    [2x1 int32]

>> read_current_item_cells{1}
ans = 
    'appl'
    'msft'

>> read_current_item_cells{2}
ans =
          12
          23

但有趣的是

>> iscell(read_current_item_cells{1})
ans =
     1

>> iscell(read_current_item_cells{2})
ans =
     0

这意味着%s对应的单元格元素变成了单元格数组,而%d对应的单元格元素保留为数组。现在,由于我不知道文件中行的确切格式,我猜你有一个单元格数组,其中一个元素又是另一个包含表中所有元素的单元格数组。

【讨论】:

    【解决方案2】:

    可能发生的情况是数据被包装到一个元胞数组的元胞数组中,并且要访问存储的字符串,您需要使用

    索引超过第一个数组
    read_current_item_cells = read_current_item_cells{1};
    

    如果您的字符串长度不相等,则从cell2mat 转换将不起作用,在这种情况下您可以使用strvcat

    read_current_item = strvcat(read_current_item_cells{:});
    

    那么你应该可以循环遍历char 数组:

    for ii=1:size(read_current_item,1)
    
     current_stock = read_current_item(ii,:); 
     current_url = sprintf('http:/www.', current_stock)
     .....
    

    【讨论】:

    • @PeterHummer 如果你觉得它有帮助,接受答案会很好。
    猜你喜欢
    • 2016-03-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    相关资源
    最近更新 更多