Reading numerical data from text fles with string
이전 댓글 표시
Dear all,
I will really appreciate f you help me out in this regards. I am using follwing code to read multiple text files and genrating a data based on specific columns. I now wanted to read the numeric values from line 10 and 11 and place them in first and column of data and repeat them for all the values of a specific cell array. Based on new cell array, the values should change till the end of that array and so on.....
clear;
D = 'T:\Intelli_test\New\files';
S = dir(fullfile(D, '*.txt'));
N = length(S);
% A = cell(N,1);
fmt = '%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f';
for k = 1:N
fid = fopen(fullfile(D,S(k).name), 'r');
A(k)= textscan(fid, fmt, 'Delimiter', '\t', ...
'headerlines', 33, ...
'CollectOutput', 1);
fid=fclose(fid);
M = vertcat(A{:});
out = M(:,[9,11]);
data=out;
end
i am now trying to add a loop like this to get the values but i am getting nothing
for k = 1:N
fid = fopen(fullfile(D,S(k).name), 'r');
linenum = 10;
h(k)= textscan(fid,'%f',1,'delimiter','\n', 'headerlines',linenum-1);
fid=fclose(fid);
end
댓글 수: 1
Note that this line
M = vertcat(A{:});
and the ones that follow it until the end of the loop should go after the loop.
There is no point in calling them inside the loop like that.
채택된 답변
추가 답변 (1개)
fadzhi
2021년 2월 2일
0 개 추천
댓글 수: 4
Mathieu NOE
2021년 2월 2일
ok , so Ifixed the problem by selecting only the first numerical field
tested for lines 6 to 11 all together - so far so good :
n_lines = (6:11); % define lines to read
result = zeros(N,numel(n_lines));
for k = 1:N
fid = fopen(fullfile(D,S(k).name), 'r'); % open file
for n = 1:numel(n_lines)
str = textscan(fid, '%s', 1, 'Headerlines', n_lines(n)-1, 'Delimiter' ,'\n'); % change %s (string) to %f to get first numerical value (does not work ??)
tmp = regexp(char(str{1}),'-?\d+\.?\d*|-?\d*\.?\d+','match'); % extract numerical content of string
tmp2 = tmp(1);
result(k,n) = str2num(tmp2{:});
frewind(fid) % set file position back to the start
end
fclose(fid); % close file
end
Mathieu NOE
2021년 2월 2일
this is another alternative using extractBetween , if you have release above R2017a
n_lines = (6:11); % define lines to read
result = zeros(N,numel(n_lines));
for k = 1:N
fid = fopen(fullfile(D,S(k).name), 'r'); % open file
for n = 1:numel(n_lines)
str = textscan(fid, '%s', 1, 'Headerlines', n_lines(n)-1, 'Delimiter' ,'\n'); % change %s (string) to %f to get first numerical value (does not work ??)
tmp2 = extractBetween(char(str{1}),':','[');
result(k,n) = str2num(tmp2{:});
frewind(fid) % set file position back to the start
end
fclose(fid); % close file
end
fadzhi
2021년 2월 2일
Mathieu NOE
2021년 2월 2일
Glad it helped !
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
