How to read a TXT file and get dynamically named string variables for each line of text?

Hi everyone!
I'm new to both this community and to MATLAB, and would like to thank you all in advance for your patience and support!
As a part of an e-mail notification project, I must transfer the contents from certain logs, while retaining all the lines and spacing of their specific formats. So, here's the code I have written so far:
% Gets the number of lines in the Text File
Nrows = numel(textread('CP89-Fermentation-Log.TXT','%1c%*[^\n]'));
% Opens the Text file, reads each line, and puts it into an array that is:
% ['1' Column x 'Nrows' Rows]
fid = fopen('CP89-Fermentation-Log.TXT','r');
InputText = textscan(fid,'%s', Nrows, 'delimiter','\n');
% Loop to produce dynamically named string variables
for k=1:Nrows
c = strcat(InputText{k});
% Evaluate this code: varname_k = sprintf('%s' , c{k});
eval('varname_' num2str(k) '= sprintf("%s " , c{' k '})');
end
Everything works except the dynamic variable loop, can someone please help me with the syntax of this, or perhaps give an alternative solution to my problem? Thanks!

Answers (2)

Welcome to MATLAB and the community!
First things first - DON'T DO WHAT YOU'RE TRYING
By the way, calculating Nrows is not needed. You can just textscan() without any limiting count, and then length(InputText) is Nrows.

1 Comment

Hello, and thank you for your reply!
The biggest problem with using an array for me is the fact that it does not work with this MATLAB function that sends e-mail from outlook. This is what the email function looks like:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sendolmail(to,subject,body,attachments)
%Sends email using MS Outlook. The format of the function is
%Similar to the SENDMAIL command.
% Create object and set parameters.
h = actxserver('outlook.Application');
mail = h.CreateItem('olMail');
mail.Subject = subject;
mail.To = to;
mail.BodyFormat = 'olFormatHTML';
mail.HTMLBody = body;
% Add attachments, if specified.
if nargin == 4
for i = 1:length(attachments)
mail.attachments.Add(attachments{i});
end
end
% Send message and release object.
mail.Send;
h.release;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The function above will only accept a string variable (AKA character array), so it refuses to read my entire array of strings...
Perhaps there's a completely different way around this? A way to import the contents while keep the formatting of the original TXT file? Thanks again!

Sign in to comment.

Asked:

on 3 Feb 2012

Community Treasure Hunt

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

Start Hunting!