【问题标题】:How to import in Matlab a cellarray from a .txt file with columns as "text"?如何在 Matlab 中从 .txt 文件中导入单元阵列,其中列为“文本”?
【发布时间】:2015-02-18 14:38:44
【问题描述】:

我有一个 .txt 文件,我想用 Matlab 中的代码作为单元格导入该文件。此 .txt 文件包含不同长度的行,其中包含数字和字符的组合。以下是文件示例:

*** After labeling ***
Elements: E11, E21, E31, E51, E61, E81, 
Connections: E11E61, E21E81, E31E61, E31E81, E51E81, 
*** After labeling ***
Elements: E11, E21, E31, E51, E61, E81, 
Connections: E11E61, E21E81, E31E51, E31E81, E61E81, 
*** After labeling ***
Elements: E11, E21, E31, E51, E61, E62, E81, 
Connections: E11E61, E21E81, E31E51, E31E62, E61E81, E62E81, 

结果应如下所示:

当我使用导入工具导入文件时,一些列被识别为 text,而一些列被识别为 numbers。我必须手动将每个列的类型从数字更改为文本:

更多,我每次都必须选择 cellarray 而不是 Column Vectors。行的最大长度是已知的,15。

我尝试了 results = importfile('results') 但它不起作用。有人对我有什么建议吗?

【问题讨论】:

    标签: matlab import cell-array


    【解决方案1】:

    这是一些简单的解析例程,它直接返回 elementsconnections 作为单元向量。

    注意:解析假定文本文件格式正确,并且始终是元素,然后是连接。

    function [elements, connections] = ReadElementsAndConnections(filename)
    %[
        % For debug
        if (nargin < 1), filename = 'ElementsAndConnections.txt'; end
    
        % Read full file content
        text = fileread(filename);
    
        % Split on newline
        lines = strsplit(strtrim(text), '\n');
    
        % Parse
        elements = cell(0,1);
        connections = cell(0,1);
        isElementLine = true;
        lcount = length(lines);
        startElements = length('Elements:') + 1;
        startConnections = length('Connections:') + 1;
        for li = 1:lcount,
    
            % Skip empty lines or lines starting with '*'
            line = strtrim(lines{li});
            if (isempty(line) || (line(1) == '*')), continue; end
    
            % NOT VERY SAFE: Assuming we always have 'elements', followed by 'connections'
            if (isElementLine)
                elementsLine = lines{li}(startElements:end);
                elementsValues = strtrim(strsplit(elementsLine, ','));
                elements{end+1} = elementsValues(1:(end-1)); % Last value is empty.
                isElementLine = false;
            else
                connectionsLine = lines{li}(startConnections:end);
                connectionsValues = strtrim(strsplit(connectionsLine, ','));
                connections{end+1} = connectionsValues(1:(end-1)); % Last value is empty.
                isElementLine = true;
            end
    
        end
    %]
    end
    

    然后您可以像这样访问elementsconnections

    >> elements{1}
    
    ans = 
    
        'E11'    'E21'    'E31'    'E51'    'E61'    'E81'
    
    >> connections{3}
    
    ans = 
    
        'E11E61'    'E21E81'    'E31E51'    'E31E62'    'E61E81'    'E62E81'
    

    【讨论】:

    • 非常感谢。完美运行。拥有格式良好的文件的假设是正确的。我还有一点要说:由于我的完整代码需要输入一个单元格,其中“E11”和“E21”位于不同的列上,因此我必须根据您的结果构建它。我正在做。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多