Skip to Main Content Skip to Search
Home |   Select Country  Choose Country  |  Contact Us  |  Cart Store 
Create Account | Log In
Products & Services Solutions Academia Support User Community Company
spacer spacer spacer spacer spacer spacer

Technical Solutions

How do I read in mixed ASCII and numeric data?


Date Last Modified: Tuesday, November 17, 2009
Solution ID:   1-15VVF
Product:   MATLAB
Reported in Release:   No Release
Platform:   All Platforms
Operating System:   All OS
 

Subject:

How do I read in mixed ASCII and numeric data?

Problem Description:

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.

Solution:

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);

Please provide feedback to help us improve this Solution
Contact support
E-mail this page
Print this page