2016-12-01 64 views
0

也許這個問題很奇怪,但無論如何.... 如何讀取變量的值(字符串或數字)number_of_plotscolor? (我想用變量/排列圖選項來解決這個問題)Matlab:如何讀取變量的值(字符串或數字)?

我的代碼:

diagramoptions = []; 
wholecontent = fileread('aaa.txt') 
sections = regexp(wholecontent, '\*+([^*]+)\*+([^*]+)', 'tokens') 
for section = sections 
    switch(strtrim(section{1}{1})) 
     case 'Diagram Options' %Diagram Options -> siehe meine Gliederung im .txt file 
      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 
openvar diagramoptions 

我輸入 「aaa.txt」:

******************* Diagram Options**************** 
number_of_plots=4 
header=Number of cycles 
color=red 
xlabel= RPM 
ylabel= degree 

回答

1

這裏有一個簡單的方式這樣做......它不能很好地擴展,它做了不必要的工作..但它是你需要建立的東西。

fileId = fopen('test.txt'); 
c = textscan(fileId, '%s', 'Delimiter', '='); 
fclose(fileId); 

for i = 1: length(c{1,1}) 
    if (strcmp(c{1,1}{i,1}, 'number_of_plots')) 
     number_of_plots = c{1,1}{i+1,1}; 
    elseif strcmp(c{1,1}{i,1}, 'color') 
     color = c{1,1}{i+1,1}; 
    end 
end 

因此,讀取該文件中,並在=劃會讓你知道,在任何例如匹配number_of_plots在下一行。所以只需循環並挑選出來。

+0

好的,謝謝。有用。但在我看來有點複雜....必須有一個簡單的方法......如果你打開「openvar圖表選項」,你會發現第一列的名稱爲Key,第二列的名稱爲Value。所以我認爲你必須問「哪個值有關鍵」number_of_plots「,但我不知道該怎麼做...... – Lutz

+0

你的問題是解決它..而我不明白爲什麼它很複雜?它基本上2如果語句清楚地讀到了什麼..但它肯定是比我自己的應用程序中寫的更多的代碼行(我在年齡中沒有使用過Matlab) – Algar

0

您可以使用該功能eval爲了運行一個.txt文件,因爲它是一個.m文件:

fid = fopen('aaa.txt') %open the file 

tline = fgetl(fid); %read the first line 
while ischar(tline) 
if ~isempty(strfind('tline','number_of_plots')) | ~isempty(strfind('tline','color=')) 
     try %if it's possible matlab execute this line 
     eval(tline) 
     end 
end 
    tline = fgetl(fid); %read the next line 
end 

fclose(fid) 

但在這種情況下,你需要一些引號添加到您的aaa.txt如此該matlab可以創建變量:

******************* Diagram Options**************** 
number_of_plots=4 
header='Number of cycles' 
color='red' 
xlabel='RPM' 
ylabel='degree' 
+0

你好,我需要來自圖表選項的信息....我知道結果是相同的,如果我評估.txt文件 - 但我的.txt文件的結構正在改變... – Lutz

+0

所以只需添加一個if條件,檢查我的編輯 – obchardon