How to add rows to string array using a loop

14 views (last 30 days)
Nadeau Hahne
Nadeau Hahne on 6 Jan 2023
Answered: Voss on 6 Jan 2023
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

Answers (1)

Voss
Voss on 6 Jan 2023
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!