How to extract numbers from .dat file

37 views (last 30 days)
Nasis Vangelis
Nasis Vangelis on 11 Jan 2021
Answered: Mathieu NOE on 12 Jan 2021
Hello everyone,
I have a problem on how to open and extract from .dat files.The .dat files are like these
DEAD LOAD: 28.75
USEFULL LOAD: 10
SPANS: 2.0 1.0 3.0 4.0 5.0
and those numbers i want tο be put into some new variables which DEAD LOAD will be (q), USEFULL LOAD will be (g), SPANS will be (Li).Please if someone has an idea reply.
Thank you all for your time!
  3 Comments
Mathieu NOE
Mathieu NOE on 12 Jan 2021
hi
test also this variant :
a=readcell('data.dat',"Delimiter",":");
Nasis Vangelis
Nasis Vangelis on 12 Jan 2021
Thank you about your replies gyus,both of them are working my only problem is how i can put the numeric part of the .dat file in variables.This is what the .dat file looks like.Also i want to ask if i can use the dlmread to solve my prolem.

Sign in to comment.

Answers (2)

Star Strider
Star Strider on 12 Jan 2021
One option:
fidi = fopen('Nasis Vangelis.dat','rt');
k = 1;
while ~feof(fidi)
readline = fgetl(fidi);
C{k} = regexp(readline, '(\w*\s\w*\:)|(\w*\:)|(\d*\.*\d*)', 'match');
k = k+1;
end
fclose(fidi);
with:
C{1}
C{2}
C{3}
producing:
ans =
1×2 cell array
{'DEAD LOAD:'} {'28.75'}
ans =
1×2 cell array
{'USEFULL LOAD:'} {'10'}
ans =
1×6 cell array
{'SPANS:'} {'2.0'} {'1.0'} {'3.0'} {'4.0'} {'5.0'}
The file (renamed ‘Nasis Vangelis.txt’ since ‘.dat’ files are not permitted) is attached.

Mathieu NOE
Mathieu NOE on 12 Jan 2021
hi again
these are 3 options I tested for you ; i believe the second one is what you are looking for
a=readcell('data.dat',"Delimiter",":");
% % option 1 : create a structure :
% for ci = 1:size(a,1)
% Varnames{ci} = matlab.lang.makeValidName(a{ci,1});
% myStruct.(Varnames{ci}) = a{ci,2};
% end
% option 2 using assignin (in function variableCreator) :
for ci = 1:size(a,1)
% change blanks in varaible names to underscore (otherwise
% variableCreator will throw an error mesage
str = strrep(a{ci,1}, ' ', '_');
val = a{ci,2};
if ischar(val)
val = str2num(val);
end
variableCreator ( str, val )
end
% option 3 creating a table - one line engine !
% T = array2table(a)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function variableCreator ( newVar, variable )
assignin ( 'caller', newVar, variable );
end

Products

Community Treasure Hunt

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

Start Hunting!