Textscan on tab delimited file in MATLAB

Please I require help to make this code output the content of a file after inserting a tab and a & in-between the elements:
%Open file for reading
[FileName,PathName,FilterIndex] = uigetfile('*', 'Select the input file');
if FilterIndex
FileName = strcat(PathName,FileName);
fid = fopen(FileName);
temp = textscan(fid, '%d\t %s\t %10.6f\t %10.6f\t %10.6f\t %10.6f\n');
tmpstr1 = temp(1);
tmpstr2 = temp(2);
tmpstr3 = temp(3);
tmpstr4 = temp(4);
tmpstr5 = temp(5);
fclose(fid);
fid = fopen('MetabsArranged.txt', 'w');
A = [tmpstr1 tmpstr2 tmpstr3 tmpstr4 tmpstr5];
for k = 1:size(A)
fprintf(fid, '%d\t &\t %s\t &\t %10.6f\t &\t %10.6f\t &\t %10.6f\t &\t %10.6f\n',A{k});
end
fclose(fid)
end
Input example- a txt file:
1 Sugar 3.13E-01 4.38E-01 4.38E-01 2.19E-01
2 Histidine 6.25E-02 1.88E-01 6.25E-02 6.25E-02
Output required:
1 & Sugar & 3.13E-01 & 4.38E-01 & 4.38E-01 & 2.19E-01
2 & Histidine & 6.25E-02 & 1.88E-01 & 6.25E-02 & 6.25E-02

1 commentaire

Jan
Jan le 12 Sep 2011
Please format your code, such that it is readable. See: http://www.mathworks.com/matlabcentral/answers/13205-tutorial-how-to-format-your-question-with-markup
Did you read the "Markup help" link? If not, why?
It seems to be very hard for beginners to format the code. It would be helpful, if you describe your problems in: http://www.mathworks.com/matlabcentral/answers/12556-how-can-code-formatting-be-made-more-intuitive-for-newcomers
What does "unable to get the code to work" mean exactly? Do you get an error - which message? Does the output differ from the expectations?

Connectez-vous pour commenter.

 Réponse acceptée

Jan
Jan le 12 Sep 2011
"for k = 1:size(A)" is a bug: SIZE replied a vector. Either use LENGTH, NUMEL or specify the dimension like "SIZE(A, dim)".
As far as I understand, you can read the complete file as string and convert all tabs to "tab&tab" - correct?
Str = fread(fid_in, Inf, 'char');
Str = strrep(Str, sprintf('\t'), sprintf('\t&\t'));
fprintf(fid_out, '%s', Str);

1 commentaire

James
James le 13 Sep 2011
Hi,
I apologise for posting my code unformated - I was having some issues with the internet and web pages not displaying properly and very frustrating as well. I promise to abide by the rules and thanks for pointing them out to me.
Thank you very much for the corrections on the code. The code now works beautifully. I would be happy if you could explain to me more why "LENGTH, NUMEL or specify the dimension like "SIZE(A, dim)" might be better than SIZE in that situation.
Best wishes,
James

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Import and Export dans Centre d'aide et File Exchange

Tags

Aucun tag saisi pour le moment.

Community Treasure Hunt

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

Start Hunting!

Translated by