Extracting number after a string in header of CSV file
이전 댓글 표시
Hello, I have a CSV file that contains information in the headers and then numerical data.
I have no problem loading the numerical tabulated data into a uitable via readtable, but I want to pick out several strings within the header too.
I particularly want to extract the numbers in these lines
1: Memory Length,1000000,
2: Horizontal Scale,2.000E-04,
3: Sampling Period,2.000E-09,
Im nearly there but just can't quite get it:
fullpath=fullfile(folder,file)
l=readlines(fullpath);
Key = 'Memory Length';
line_idx=find(startsWith(l,Key))
Str=l(line_idx)
class(Str)
Index = strfind(Str, Key)
Str(Index(1) + length(Key):end)
line_idx =
2
Str =
"Memory Length,1000000,"
ans =
'string'
Index =
1
ans =
1×0 empty string array
Here is the typical file (also attached)
Format,1.0B,
Memory Length,1000000,
IntpDistance,0,
Trigger Address,-1,
Trigger Level,2.200E+00,
Source,CH1,
Vertical Units,V,
Horizontal Units,S,
Horizontal Scale,2.000E-04,
Sampling Period,2.000E-09,
Horizontal Old Scale,2.000E-04,
Horizontal Old Position,1.000E-03,
Firmware,V1.27.001,
Mode,Detail,
Waveform Data,
6.891787e-11,5.00e+00,
2.068918e-09,5.00e+00,
4.068918e-09,4.76e+00,
6.068918e-09,4.24e+00,
8.068918e-09,4.24e+00,
댓글 수: 1
Jason
2025년 2월 7일
편집: Walter Roberson
2025년 2월 7일
채택된 답변
추가 답변 (1개)
There are lots of ways to do this. Here is one modified from code I shared here: https://www.mathworks.com/matlabcentral/answers/2172834-2d-matrix-resize-or-interpolation#comment_3323358
data = readData('DummyData.txt')
plot(data.Waveform(:,1),data.Waveform(:,2))
xlabel("Time - "+data.HorizontalUnits)
ylabel("Amplitude - "+data.VerticalUnits)
function data = readData(fname)
r=0;
data = struct;
fid = fopen(fname);
while ~feof(fid)
ln = fgetl(fid);
[param,val] = strtok(ln,",");
switch param
case 'Waveform Data'
fseek(fid,0,'eof');
fgetl(fid);
otherwise
val = strtok(val,',');
pat = asManyOfPattern(characterListPattern("0123456789-+.E"));
nums = extract(val,pat);
Param = matlab.lang.makeValidName(param);
if length(val)==length(nums{1})
data.(Param) = str2double(val);
else
data.(Param) = val;
end
end
r = r+1;
end
fclose(fid);
val = readmatrix(fname,'FileType','text','NumHeaderLines',r);
data.Waveform = val;
end
댓글 수: 3
Jason
2025년 2월 7일
Jason
2025년 2월 7일
You can read about what this is doing here: https://www.mathworks.com/help/matlab/ref/matlab.lang.makevalidname.html
As an example, 'Vertical Units' cannot be used as a fieldname since it is not a valid variable name. This command converts it into a valid variable name so that the parameter name can be used as the field name in the returned structure.
matlab.lang.makeValidName('Vertical Units')
카테고리
도움말 센터 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
