How do I read in mixed ASCII and numeric data?

5 views (last 30 days)
I have a file where strings and data are mixed in the following format:
FP1 2.34 5.66 6.77 7.88
Cp6 2.44 5.55 7.77 7.88
RTP12 5.55 3.33 6.66 5.55
I would like to open this file and get the ASCII strings and numeric data into MATLAB.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 18 Oct 2016
Here are two quick example MATLAB code fragments that will read in data that is in the format:
string # # # #
This is the only format that this file can read. If your data is in a different format, you will need to adjust the FSCANF statement accordingly.
NOTE: This is only an example and is provided, as is, without additional support. For more information on any of the functions used in this MATLAB file, type "help {function-name}".
% Find out number of rows in file
r=0;
x=0;
% Open Data File
fid = fopen('data.dat','rt');
% Loop through data file until we get a -1 indicating EOF
while(x~=(-1))
x=fgetl(fid);
r=r+1;
end
r = r-1;
disp(['Number of rows = ' num2str(r)])
frewind(fid);
for i = 1:r
name = fscanf(fid,'%s',1); % Filter out string at beginning of line
num = fscanf(fid,'%f %f %f %f\n')'; % Read in numbers
if(i==1)
names = name; % Add 1st text string
result = num; % Add 1st row
else
names = str2mat(names,name); % Add next string
result = [result;num]; % Add additional rows
end
end
fclose(fid);
disp(' ')
disp('Data read in successfully:')
disp(result)
disp(' ')
disp('Strings read in successfully:')
disp(names)
disp(' ')
The following code will read the data and ignore the characters,
fid = fopen('data.dat','r');
b = fscanf(fid,'%*s %g %g %g %g');
b=[reshape(b,4,3)]'
fclose(fid);

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!