How to load .dat files containing 1st row and 2nd row as text string and remaining as .dat file format in matlab?
조회 수: 2 (최근 30일)
이전 댓글 표시
File format is shown below:
Test analysis
ABCD to EFG Solution 1+ 234.021 m
2004.00136 9.52602 0.00167
2004.00410 9.52649 0.00163
2004.00683 9.52660 0.00162
2004.00956 9.52682 0.00162
2004.01229 9.52638 0.00165
2004.01503 9.52665 0.00167
2004.01776 9.52728 0.00163
2004.02049 9.52750 0.00162
2004.02322 9.52809 0.00161
2004.02595 9.52774 0.00164
2004.02869 9.52838 0.00164
2004.03142 9.53009 0.00159
2004.03415 9.52968 0.00161
2004.03688 9.52793 0.00161
2004.03962 9.52739 0.00162
2004.04235 9.52801 0.00162
2004.04508 9.52890 0.00161
2004.04781 9.52899 0.00161
2004.05054 9.52808 0.00162
2004.05328 9.52920 0.00162
2004.05601 9.52847 0.00162
2004.05874 9.52863 0.00161
I want to read the file and extract the value from the second row given as 234.021 and add to the 2nd column of each row.
Kindly help me!
댓글 수: 0
답변 (1개)
Geoff Hayes
2014년 8월 25일
Chris - do you have to do this for multiple files, or is it just the one file? It almost seems simpler to just use textscan to read in the numeric data (skipping the two text/header lines) and then add the number to the second column. Something like
fid = fopen('yourTextFile.txt');
if fid > 0
C = textscan(fid,'%f %f %f','HeaderLines',2);
C{2} = C{2} + 234.021;
fclose(fid);
end
In the above, C is a cell array of size three, one element for each column of data read in from the file. We take the second one and add the 234.021 to it, close the file and we are done.
If you have multiple files, does the second line always have the same format of
ABCD to EFG Solution 1+ 234.021 m
so that the number you are interested in is in between the + symbol and the m i.e. the last number in the string? If so, you could rework the above to
fid = fopen('yourTextFile.txt');
if fid > 0
% get the first line of text
str = fgetl(fid);
% get the second line of text
str = fgetl(fid);
% remove all characters that aren't numeric, period, dash (for negative) and space;
% and convert to numeric array
numericArray = str2num(regexprep(str,'[^0-9.\s-]',''));
% get the last value which will be added to the second column
if ~isempty(numericArray)
valToAdd = numericArray(end);
C = textscan(fid,'%f %f %f');
C{2} = C{2} + valToAdd;
end
fclose(fid);
end
Try either of the above and see what happens!
댓글 수: 2
Geoff Hayes
2014년 8월 25일
regexprep(str,'[^0-9.\s-]','')
is replacing everything in str that is not a value between 0 and 9 (0-9), is not a period/decimal (.), is not whitespace (\s) and is not a dash/negative (-), with an empty string ''. So the ^ is the not indicating to not replace anything that is defined within the square brackets.
참고 항목
카테고리
Help Center 및 File Exchange에서 Language Support에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!