How can I process each line or word in a text file using MATLAB?

1 view (last 30 days)
The contents of the text file are in this format, where each line consists of two names with a number attached with an underscore:
Abdel_Madi_Shabneh_0001 Dean_Barker_0001
Abdel_Madi_Shabneh_0001 Giancarlo_Fisichella_0001
Abdel_Madi_Shabneh_0001 Mikhail_Gorbachev_0001
Abdul_Rahman_0001 Portia_de_Rossi_0001
Abel_Pacheco_0001 Jong_Thae_Hwa_0002
Abel_Pacheco_0002 Jean-Francois_Lemounier_0001
and I'd like to reformat the content to make it like this, in other words but them into cell of nX2 dimension so I can each them easily:
'Abdel_Madi_Shabneh_0001' 'Dean_Barker_0001';
'Abdel_Madi_Shabneh_0001' 'Giancarlo_Fisichella_0001';
'Abdel_Madi_Shabneh_0001' 'Mikhail_Gorbachev_0001';
'Abdul_Rahman_0001' 'Portia_de_Rossi_0001';
'Abel_Pacheco_0001' 'Jong_Thae_Hwa_0002';
'Abel_Pacheco_0002' 'Jean-Francois_Lemounier_0001';
Is there a way how can I do it automatically? Thanks
  2 Comments
Jan
Jan on 1 Nov 2015
Edited: Jan on 1 Nov 2015
Where do you want this result ro appear? In a text file or is this a cell string? Is the indentation of the 2nd column important? Are there leading spaces in the text file or does this appear in the forum only?
Alaa
Alaa on 1 Nov 2015
it doesn't matter, the output in the text or cell. and yes I want them sorted as a array of two columns,. yes, there are space between each pair and all the text formatted exactly as shown in the forum.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 1 Nov 2015
Edited: Stephen23 on 1 Nov 2015
Just use textscan:
fid = fopen('temp.txt','rt');
C = textscan(fid,'%s%s');
fclose(fid);
C = cat(2,C{:});
to get this:
>> C
C =
'Abdel_Madi_Shabneh_0001' 'Dean_Barker_0001'
'Abdel_Madi_Shabneh_0001' 'Giancarlo_Fisichella_0001'
'Abdel_Madi_Shabneh_0001' 'Mikhail_Gorbachev_0001'
'Abdul_Rahman_0001' 'Portia_de_Rossi_0001'
'Abel_Pacheco_0001' 'Jong_Thae_Hwa_0002'
'Abel_Pacheco_0002' 'Jean-Francois_Lemounier_0001'
The example text file is attached here:

More Answers (0)

Community Treasure Hunt

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

Start Hunting!