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!