How to extract numbers from .dat file

조회 수: 6 (최근 30일)
Nasis Vangelis
Nasis Vangelis 2021년 1월 11일
답변: Mathieu NOE 2021년 1월 12일
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에서 Programming에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by