Maybe the question is strange but anyway.... How can i read the value (string or number) of the variable number_of_plots or color ? (i want to use the variable/array diagram options to solve this problem)
My Code:
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
My Input "aaa.txt":
******************* Diagram Options****************
number_of_plots=4
header=Number of cycles
color=red
xlabel= RPM
ylabel= degree
Here's a naive way of doing it... It doesn't scale well and it does unnecessary work.. But it's something for you to build upon.
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
So, read in the file and delimit at =
makes you know that any match on eg number_of_plots
is in the next row. So just loop through and pick it out.
You can use the function eval
in order to run a .txt file as it was a .m file:
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)
But in this case you need to add some quotation marks to your aaa.txt so that matlab can create the variables:
******************* Diagram Options****************
number_of_plots=4
header='Number of cycles'
color='red'
xlabel='RPM'
ylabel='degree'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.