如何在 Matlab 中从列为 "text" 的 .txt 文件导入 cellarray?

How to import in Matlab a cellarray from a .txt file with columns as "text"?

我有一个 .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。我必须手动将列的类型从数字更改为文本:

此外,我每次都必须 select cellarray 而不是列向量。行的最大长度已知,15.

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

下面是一些简单的解析例程,returns直接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'