2017-01-10 11 views
0

私の入力ファイル(test_input.txt)から特定のデータを読みたいです。計算と設定にこのデータが必要です。Matlab:変数から値を読み込む?

私のtest_input.txtファイルの入力変数wsectionstart以外はすべて動作します。

wsectionstart = NaN

私の質問は、私はすべてのエラーメッセージなしでこの変数を読むことができる方法です:私は、全体のコードを実行すると

は、私は、出力メッセージが表示されます。だから私はwsectionstartwsectionstart(1)またはwsectionstart(2)のようなすべての単一の値を読むことができます。コードをどのように変更すればよいですか?

次のコードは、私の全体のコードからほんの減少一部です:

diagramoptions = []; 

wholecontent = fileread('test_input.txt'); 

sections = regexp(wholecontent, '\*+([^*]+)\*+([^*]+)', 'tokens'); 

for section = sections 

    switch(strtrim(section{1}{1})) 

     case 'Diagram Options' 

      keyvalues = regexp(section{1}{2}, '([^\n\r=]+)=([^\n\r=]+)', 'tokens'); %\n -> new line; \r carriage return 

      diagramoptions = cell2table(vertcat(keyvalues{:}), 'VariableNames', {'Key', 'Value'}); 

     otherwise 

      warning('Unknown section: %s', section{1}{1}), 

    end 

    end 

linewidth=str2double(diagramoptions.Value(strcmp(diagramoptions.Key, 'linewidth'))); %works 

xlabel=diagramoptions.Value(strcmp(diagramoptions.Key, 'xlabel')); %works 

wsectionstart=str2double(diagramoptions.Value(strcmp(diagramoptions.Key, 'wsectionstart'))) 

そして、これはここに私のtest_input.txtファイル

******************* Diagram Options**************** 
linewidth=12 
wsectionstart=1000000 3000000 
xlabel= Capture 
+0

期待される出力は何ですか?テキストファイルのどの値を保存したいのですか?どのように保存しますか?あなたのコードからこれを判断することは非常に困難です。 – rayryeng

+0

変数 "wsectionstart"には2つの値があります - > test.txtを参照してください。私は、最初の値と2番目の値を読み取り、配列に格納したい。 – Lutz

+0

あなたのファイルは 'test_input.txt'と呼ばれていますが、あなたのコードでは' test.txt'として読み込みます...それは? – Wolfie

答えて

0

コードです:

  • 読み込みテーブルとしてtxtファイルにreadtable
  • str2double
  • を使用して数値を文字列から関連する値を変換し、ファイル内のものがcellそのままTは中括弧を使用して索引付けされなければならないこと

    % Create table from formatted input txt file (see below) 
    T = table2array(readtable('test_input.txt')); 
    
    % Initialise & populate variables from table 
    wsectionstart = zeros(1,2); 
    wsectionstart(1) = str2double(T{2,2}); 
    wsectionstart(2) = str2double(T{2,3}); 
    linewidth = str2double(T{1,2}); 
    xlabel = T{3,2}; 
    

注に基づいて、すべての入力変数を割り当て。

Option,   Value1,  Value2 
linewidth,  12,   - 
wsectionstart, 1000000, 3000000 
xlabel,   Capture, - 

はコンマはあなたが好きなようキー、スペースこの出ているが、列は各コンマ区切り文字と行から読み込まれます。これは、より適切に構造化入力ファイル(test_input.txt)あなたより、以下のようにレイアウトが必要ですファイルの各行から

自分のコードではなく自分のコードを使用しても問題はありませんが、質問の編集の1つが、行末にセミコロンのコンマ,を置き換えています。これは正しい修正ですが、起こったことを忘れているかもしれません。

関連する問題