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!
回答(2 个)
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.
0 个评论
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
0 个评论
另请参阅
类别
在 Help Center 和 File 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!