Chage commas with dots in sequential txt files?

2 vues (au cours des 30 derniers jours)
Enrico Zanazzi
Enrico Zanazzi le 7 Jan 2019
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.

Réponses (1)

Star Strider
Star Strider le 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'}

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by