如何在Matlab中导入一个.txt文件中的cellarray,列为“text”?

时间:2015-02-17 20:20:35

标签: matlab import cell-array

我有一个.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, 

结果应如下所示:

enter image description here

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

enter image description here

更多,我每次都必须选择 cellarray 而不是列向量。线的最大长度是已知的,15。

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

1 个答案:

答案 0 :(得分: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'