How to read a TXT file and get dynamically named string variables for each line of text?
Show older comments
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)
Sean de Wolski
on 3 Feb 2012
0 votes
Walter Roberson
on 3 Feb 2012
0 votes
By the way, calculating Nrows is not needed. You can just textscan() without any limiting count, and then length(InputText) is Nrows.
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!