read a file and covert it to two arrays

2 views (last 30 days)
Robert Jones
Robert Jones on 22 Feb 2019
Answered: Robert Jones on 23 Feb 2019
I have an ascii data file with the following content:
a=2
b=4
c=9
I need to read it and create two arrays: one containing the names of the variables and another containing the values of the variables, i.e.
vn=[a b c];
vv=[2 4 9];
I have no control on the input file, it's just given to me.
Any ideas?
Thanks
Robert

Answers (3)

Robert Jones
Robert Jones on 22 Feb 2019
here it is

Image Analyst
Image Analyst on 22 Feb 2019
Try this (untested)
% Open the file.
fileID = fopen(fullFileName, 'rt');
loopCounter = 1;
% Read the first line of the file.
textLine = fgetl(fileID);
while ischar(textLine)
equalLocation = strfind(textLine, '=')
ca{loopCounter, 1} = textLine(1:(equalLocation-1));
ca{loopCounter, 2} = str2double(textLine((equalLocation+1):end))
% Read the remaining lines of the file.
fprintf('%s\n', textLine);
% Read the next line.
textLine = fgetl(fileID);
loopCounter = loopCounter + 1;
end
% All done reading all lines, so close the file.
fclose(fileID);
ca is your cell array output.
  4 Comments
Robert Jones
Robert Jones on 22 Feb 2019
I see,
this how I solved the problem, not sure if this is the most elegant, but vn=[a b c] and qq=[5,3,9]
Thank you
clc
clear all
fullFileName='data.txt';
% Open the file.
fileID = fopen(fullFileName, 'rt');
loopCounter = 1;
% Read the first line of the file.
textLine = fgetl(fileID);
while ischar(textLine)
equalLocation = strfind(textLine, '=');
ca{loopCounter, 1} = textLine(1:(equalLocation-1));
ca{loopCounter, 2} = textLine((equalLocation+1):end);
% Read the remaining lines of the file.
fprintf('%s\n', textLine);
% Read the next line.
textLine = fgetl(fileID);
loopCounter = loopCounter + 1;
end
% All done reading all lines, so close the file.
fclose(fileID);
vn=char(ca{:,1});
vv=char(ca{:,2});
for i=1:size(vv)
qq(i)=str2double(vv(i));
end
Image Analyst
Image Analyst on 23 Feb 2019
You're right. Not elegant. No need at all for a second loop. If you want a numerical/double vector, qq, then just simply put qq into the loop instead of ca{loopCounter, 2}:
qq(loopCounter) = str2double(textLine((equalLocation+1):end))
And the reason I used a cell array instead of a character array is to be robust enough to handle possible cases where the letters before the equals sign are more than one, like a two letter variable instead of a one letter variable. If you know for a fact that you will ALWAYS have single letters then you can just put your vn into the loop along with the qq. Again, just a single for loop is needed, NOT two.

Sign in to comment.


Robert Jones
Robert Jones on 23 Feb 2019
Thank you

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!