1

I am reading a text file into Matlab called 'test.txt' which is structured as follows:

$variable1 = answer1; 
$variable2 = answer2;
$variable3 = answer3;

I read the text file into Matlab line by line using the following segment of code:

fid = fopen('test.txt.');
tline = fgetl(fid);
tracks = {};
while ischar(tline)
    tracks{end+1} = regexp(tline, '(?<=^.*\=\s*)(.*)(?=\s*;$)', 'match', 'once');
    tline = fgetl(fid);
end
fclose(fid);

This piece of code returns the value of each variable line by line and would output:

answer1
answer2
answer3

What I want to do is modify my regexp expression so that I can specify the name of the variable to retrieve and have Matlab output the value assigned to the variable specified.

E.g. If I specify in my code to find the value of $variable2, Matlab would return:

answer2

Regards

1 Answer 1

2

One possible solution:

function [tracks] = GetAnswer(Filename, VariableName)
fid = fopen(Filename);
tline = fgetl(fid);
tracks = {};

% prefix all $ in VariableName with \ for `regexp` and `regexprep`
VariableName = regexprep(VariableName, '\$', '\\$');

while ischar(tline)
    if (regexp(tline, [ '(', VariableName, ')', '( = )', '(.*)', '(;)' ]))
        tracks{end+1} = regexprep(tline, [ '(', VariableName, ')', '( = )', '(.*)', '(;)' ], '$3');
        % if you want all matches (not only the 1st one),
        % remove the following `break` line.
        break;
    end
    tline = fgetl(fid);
end

fclose(fid);
return

You can call it this way:

Answer = GetAnswer('test.txt', '$variable2')

Answer = 
'answer2'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.