How to read certain data within a text file.

Hi. I would like to read some matrices and vectors from a txt file. This one has got many sets of four problems per set, and in each of those problems there are two vectors and one matrix as the data of the problem. That being said, my goal is to extract just the matrix and the vectors from all the problems of an specific set, but I'm having some troubble when doing it. I know how to read all the lines of the file, but I just want the "pointer" to stop when it finds my set of problems.
For example, if you open the file I've attached, I just want to read all the matrices and vectors of the set of problems that contains in its title: "cjt. de dades 51".
Thank you very much.

 Respuesta aceptada

Mathieu NOE
Mathieu NOE el 10 de Nov. de 2021
hello Ivan
this is my suggestion
dades 51 : there are 4 problems in this case and the code will ouput cell arrays of size 4 for vectors c and b and matrices A
%%%%%%%% main code %%%%%%%%%
clc
clearvars
filename = 'Enunciats.txt';
str = "dades 51";
[A_data,B_data,C_data] = myfunction_read(filename,str)
%%%%%%% functions %%%%%%%%%
function [A_data,B_data,C_data] = myfunction_read(filename,str)
lines = readlines(filename,'WhitespaceRule','trim');
% init data
start_line_index = Inf;
sections = 1;
c_line_index = [];
A_line_index = [];
b_line_index = [];
for ci = 1:numel(lines)
ll = lines(ci);
if contains(ll,str) %
start_line_index(sections) = ci;
sections = sections+1;
end
if contains(ll,"c=")
c_line_index = [c_line_index; ci+1];
end
if contains(ll,"A=")
A_line_index = [A_line_index; ci+1];
end
if contains(ll,"b=")
b_line_index = [b_line_index; ci+1];
end
end
%% remove a,B,c lines index that are not compatible with start_line_index
% for "b"
[~,ind_last_b_line] = min(abs(b_line_index-max(start_line_index)));
ind_last_b_line = ind_last_b_line+1;
sections = sections-1;
ind_b_lines = ind_last_b_line - sections +1:ind_last_b_line;
b_data = lines(b_line_index(ind_b_lines));
[m,~] = size(b_data);
for ck = 1:m
B_data{ck} = str2num(b_data(ck,1));
end
% for "c"
c_data = lines(c_line_index(ind_b_lines));
[m,~] = size(c_data);
for ck = 1:m
C_data{ck} = str2num(c_data(ck,1));
end
% for "A"
A_start_lines = A_line_index(ind_b_lines);
A_stop_lines = b_line_index(ind_b_lines)-3;
[m,~] = size(A_start_lines);
for ck = 1:m
tmp = lines(A_start_lines(ck):A_stop_lines(ck),1);
A = cellfun(@str2num, tmp, 'UniformOutput', false);
A_data{ck} = cell2mat(A);
end
end

2 comentarios

Thank you very much. It works perfectly!!
Mathieu NOE
Mathieu NOE el 12 de Nov. de 2021
My pleasure !

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre File Operations en Centro de ayuda y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by