Using textscan wisely, different data type

2 views (last 30 days)
Asher Metzger
Asher Metzger on 2 Aug 2015
Edited: dpb on 3 Aug 2015
Hi there, I'm trying to read lines from a text file and then alter one of the numbers. a line looks like this:
1 1 2 3535.68 4572 120 0 Closed ;
I want change the 6th number (120). this is what i did and I know it's ugly:
a=textscan(tline{i},'%s %s %s %s %s %d %s %s %s');
newl=i-s1+1;
b=[a{1}{1} ' ' a{2}{1} ' ' a{3}{1} ' ' a{4}{1} ' ' a{5}{1} ...
' ' num2str(aa(newl,end)) ' '...
a{7}{1} ' ' a{8}{1} a{9}{1}];
tline{i}=b;
What would be an elegant to achieve my purpose? Thanks, Asher

Answers (1)

dpb
dpb on 2 Aug 2015
Edited: dpb on 3 Aug 2015
Presuming the file is regular in format, something on the lines of
fmt=[repmat('%f',1,7) '*%s ;']; % format string
fid=fopen('thefile');
data=cell2mat(textscan(fid,fmt,'collectoutput',1));
Now you'll have one array of doubles ignoring the last column of string data.
Then simply iterate thru the rows of the array making the numeric substitution in memory where needed either by looking for particular values if that's the basis for making the change or by position in the array if that is, instead, the determining factor. You give no indication on the "why" in choosing the 120 value for the change so we don't know that.
Then, you can rewrite the file with the specific format if that's important or with a generic export routine if it isn't.
ADDENDUM Oh, you'll have to retrieve the string as well to rewrite the full in toto so you'll end up w/ a cell array w/ a numeric array and the cell string when take out the * of the '*%s' part of the format string...the previous will still hold for making the numeric changes as before.

Categories

Find more on Large Files and Big Data 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!