How to extract numbers from .dat file

39 次查看(过去 30 天)
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 个评论
Mathieu NOE
Mathieu NOE 2021-1-12
hi
test also this variant :
a=readcell('data.dat',"Delimiter",":");
Nasis Vangelis
Nasis Vangelis 2021-1-12
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.

请先登录,再进行评论。

回答(2 个)

Star Strider
Star Strider 2021-1-12
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 2021-1-12
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

类别

Help CenterFile Exchange 中查找有关 Workspace Variables and MAT-Files 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by