2015-02-17 60 views
1

我有一個.txt文件,我想用Matlab中的代碼作爲單元格導入。這個.txt文件具有不同長度的行以及它們中的數字和字符的組合。下面是該文件的一個示例:如何在Matlab中導入一個帶有「text」列的.txt文件中的cellarray?

*** 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

當我使用導入工具中的文件中的一些列被認可as text and some as numbers。我必須手動將列的類型從編號更改爲每個文本的文本:

enter image description here

更多的,我必須選擇cellarray而不是每次列向量。線的最大長度是已知的,15.

我試過results = importfile('results')但它不起作用。有人對我有任何建議嗎?

回答

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' 
+0

非常感謝。完美的作品。具有格式良好的文件的假設是正確的。我還有一點評論:因爲我的完整代碼需要輸入一個單元格,其中'E11'和'E21'在不同的列上,我將不得不從結果中構建它。我正在做。 :) – Aquila 2015-02-19 16:06:07

+0

一切都解決了! :) 再次感謝! – Aquila 2015-02-19 16:54:03

+0

不客氣! – CitizenInsane 2015-02-19 16:59:45

相關問題