Reputation: 185
I am currently trying to read data from a text file written exactly like this:
Height = 10
Length = 10
NodeX = 11
NodeY = 11
K = 10
I've written a small code like this
fileID = fopen('input.dat','r');
[a, b] = fscanf(fileID, '%s %f')
And I get the following answer:
a =
72
101
105
103
104
116
b =
1
It seems quite obvious I am not mananging to specify the format specification. I would like to know how to pick a string along with a float multiple times in the same file.
Upvotes: 1
Views: 139
Reputation: 12214
As the documentation for fscanf
states:
If
formatSpec
contains a combination of numeric and character specifiers, thenfscanf
converts each character to its numeric equivalent. This conversion occurs even when the format explicitly skips all numeric values (for example,formatSpec
is'%*d %s'
).
MATLAB can be annoyingly bad at reading mixed data types. One possible alternative is to read each line and split up your data using a simple regular expression:
fileID = fopen('results.txt','r');
mydata = {};
ii = 1;
while ~feof(fileID) % While we're not at the end of the file
tline = fgetl(fileID); % Get next line
mydata(ii,:) = regexp(tline, '([a-zA-Z])* = (\d*)', 'tokens');
ii = ii + 1;
end
fclose(fileID);
This returns a 5 x 1
cell array where each cell contains 2 cells (slightly annoying, but you can pull them out) that match your data. In this case, mydata{1}{1}
is Height
and mydata{1}{2}
is 10
.
Edit:
And you can flatten your cell array with a reshape
call:
mydata = reshape([mydata{:}], 2, [])';
Which turns mydata
in this case into a 5x2
cell array.
Upvotes: 2
Reputation: 14371
The fscanf
function is a low-level I/O function and is often not the best choice for such rather high-level file input. One alternative would be to use the textscan
function, which allows quite advanced format specifications:
fileID = fopen('input.dat','r');
C = textscan(fileID,'%s = %d')
which creates a 1x2 cell array. The first cell C{1}
contains another 5x1 cell, where each field contains the name of the field, e.g. 'Height'
. The second cell C{2}
contains a 5x1 vector containing all integer values from the file.
Upvotes: 2