Need help with textscan

5 views (last 30 days)
Tom
Tom on 28 Oct 2013
Commented: Tom on 28 Oct 2013
Hello,
I've been struggling with textscan for some time now, if anyone could point me in the right direction here I'd be eternally grateful.
I have a text file with data in the following format:
Eu3+ 1
10.06037350 -4.673610300 -1.834337367
1.22604929765 -2.02696902730 0.734136756877
10517.3113705 -9795.46057045 -2441.96899290
... and this is repeated (1510 times, to be precise)
What I am trying to achieve (for the time being), is simply to extract the first 5 entries and define as a vector, so in this instance I would simply want something like
C = [ Eu3+ 1 10.06 -4.67 -1.83]
and then the following 6 entries can be discarded.
I have tried multiple variants of ideas, along the lines of:
C = textscan(fid,'%s%d8%f32%f32%f32');
But I am continually failing to produce the vector mentioned above.
Please, Matlab community, can you help me?
Kind regards,
Tom

Accepted Answer

David Sanchez
David Sanchez on 28 Oct 2013
Your are mixing strings with doubles. Try this out. You'll end up with a cell array containing the heading and the first three doubles.
fid = fopen('test.txt','r');
% read as single cell
C = textscan(fid,'%s ');
fclose(fid);
C = C{1,1}(1:4)
C =
'Eu3+1'
'10.06037350'
'-4.673610300'
'-1.834337367'
  1 Comment
Tom
Tom on 28 Oct 2013
David, I think that's the ticket! Thanks so much!
Would you mind clarifying a few things for me.
What is the necessity of the 'r' in fopen?
How come the textscan is happy with the different entry types despite defining them only with '%s'?
What does the line C = C{1,1}(1:4) achieve? Is this simply placing the results in a vector of the relevent dimensions?
Again, thankyou!
Tom

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!