read a file and covert it to two arrays

2 次查看(过去 30 天)
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

回答(3 个)

Robert Jones
Robert Jones 2019-2-22
here it is

Image Analyst
Image Analyst 2019-2-22
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 个评论
Robert Jones
Robert Jones 2019-2-22
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 2019-2-23
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.

请先登录,再进行评论。


Robert Jones
Robert Jones 2019-2-23
Thank you

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by