2016-12-01 1987 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

相关问题