Chage commas with dots in sequential txt files?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
I have many txt files named as follows:
filename_0.txt
filename_1.txt
filename_2.txt
....
each file has two colums and the numbers have comma as decimal separator. I have to import all the files sequentially in matlab. If the numbers had the dots as decimal separator I would not have any problems, since the following code successufully imports all the files sequentially:
numfiles = 1000; % <-- insert num of files
mydata = cell(1, numfiles);
for k = 1:numfiles
myfilename = sprintf('filename_%d.txt', k);
mydata{k} = importdata(myfilename);
end
However, with the commas as decimal separators the previous code does not import the numbers properly. Moreover, importdata doesn not allow the user to define the decimal separator. How can I do? I cannot manually substitute the commas with dots in 1000 files.
Thank you.
0 Kommentare
Antworten (1)
Star Strider
am 7 Jan. 2019
Without an example file, it is not possible to write specific code.
I would use the textscan (link) function to read them in as strings, use the strrep (link) function to convert the commas to periods, and then store the converted file. For example:
for k = 1:numfiles
myfilename = sprintf('filename_%d.txt', k);
fidi = fopen(myfilename,'rt');
mydatacomma = textscan(fidi, '%s%s', 'CollectOutput',1);
fclose(fidi);
mydatadot{k} = strrep(mydatacomma, ',', '.');
end
NOTE — Since I do not have one of your text files to experiment with, this is UNTESTED CODE. It should work, although you may need to modify it to work with your files.
The strrep function works correctly with cells:
d = {'1,234' '2,345'
'4,319' '7,385'};
p = strrep(d, ',', '.')
p =
2×2 cell array
{'1.234'} {'2.345'}
{'4.319'} {'7.385'}
0 Kommentare
Siehe auch
Kategorien
Mehr zu String Parsing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!