Reading numerical data from text fles with string
Afficher commentaires plus anciens
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 commentaire
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.
Réponse acceptée
Plus de réponses (1)
fadzhi
le 2 Fév 2021
0 votes
4 commentaires
Mathieu NOE
le 2 Fév 2021
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
le 2 Fév 2021
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
le 2 Fév 2021
Mathieu NOE
le 2 Fév 2021
Glad it helped !
Catégories
En savoir plus sur Structures dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
