How to add rows to string array using a loop

조회 수: 14 (최근 30일)
Nadeau Hahne
Nadeau Hahne 2023년 1월 6일
답변: Voss 2023년 1월 6일
I would appreciate help on how to add data to subsequent rows of an array.
I am reading PDF file and extracting the data and simply trying to add each row of data a string array for each iteration of the loop but I have not been been able to understand how to do this
files = dir(fullfile(PDFfolder, '*.pdf'))
L = length(files)
DataCompiled = strings(L,5) %Preallocated with 5 rows
for i = 1:L
file = files(i).name;
[filepath,IDnum,ext] = fileparts(file);
%Text Extracted from PDF files
str = extractFileText(file);
NameEmail = extractBetween(str, 'From:', 'To');
Email = extractBetween(NameEmail, '<','>');
FirstName = extractBefore(Email, '.');
LastName = extractBetween(Email,'.','@');
prefix = 'ABC-';
SubjectID = [prefix,IDnum];
Data = [SubjectID FirstName LastName Email]
for
%How to iterate and build an array with subsequent rows filled in with
%each loop
end
end

답변 (1개)

Voss
Voss 2023년 1월 6일
Try something like this:
files = dir(fullfile(PDFfolder, '*.pdf'));
L = length(files);
DataCompiled = strings(L,4); %Preallocated with *4* *columns* (SubjectID, FirstName, LastName, Email)
% construct full-path file names:
file_names = fullfile({files.folder},{files.name});
for i = 1:L
% "filepath" is apparently unused, so you can replace it with "~" here,
% and "ext" is apparently unused, so you can remove it here
[~,IDnum] = fileparts(file_names{ii});
%Text Extracted from PDF files
str = extractFileText(file_names{ii});
NameEmail = extractBetween(str, 'From:', 'To');
Email = extractBetween(NameEmail, '<','>');
FirstName = extractBefore(Email, '.');
LastName = extractBetween(Email,'.','@');
% use string concatenation (+)
SubjectID = "ABC-" + IDnum;
% (but concatenation of character vectors would also work because SubjectID
% will be assigned into the string array "DataCompiled")
% SubjectID = ['ABC-',IDnum];
% put the strings in the i-th row of DataCompiled
DataCompiled(i,:) = [SubjectID FirstName LastName Email];
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by