Importing a .csv file
Show older comments
Hello everyone
I have a .csv file that contains values (juste to illustrate)
Time(S),Cur(A),Vol(V)
0,0,00,4,206
1,0,00,4,206
2,0,52,4,092
4,0,52,4,088
6,0,52,4,085
8,0,52,4,082
10,0,52,4,082
12,0,52,4,081
14,0,52,4,081
16,0,52,4,078
18,0,52,4,074
20,0,52,4,074
22,0,52,4,074
24,0,52,4,073
26,0,52,4,073
28,0,52,4,073
30,0,52,4,073
Under MATLAB, I have written the following code
data = readmatrix('Discharge_Curve.csv')
The output of this code is 5 different vectors, but that's not what I'm looking for. What I exactly want is to have 3 vectors Time(S), Cur(A), Vol(V). For example, for line 1, two commas should be replaced with dots.
0,0,00,4,206 ----->to 0,0.00,4.206
1,0,00,4,206 ----->to 1,0.00,4.206
the final results
0,0.00,4.206
...
2,0.52,4.092
...
The issue arises from my measuring instrument, which outputs the CSV file incorrectly. It doesn't distinguish between commas and dots, so it uses commas for everything.
For this, I am looking for a solution that addresses my issue.
Thank you very much for your very valuable help
Accepted Answer
More Answers (1)
Here's one way you can try to fix that file:
f_in = 'data.csv';
f_out = 'data_modified.csv';
% show the original file's contents
type(f_in)
% read the file
str = fileread(f_in);
% replace the 2nd and 4th commas on each line with periods
str = regexprep(str,'(\r?\n\d+),(\d+),(\d+),(\d+),(\d+)','$1,$2.$3,$4.$5');
% write the new file
fid = fopen(f_out,'w');
fprintf(fid,'%s',str);
fclose(fid);
% show the new file's contents
type(f_out)
% now readmatrix returns a matrix with three columns
M = readmatrix(f_out)
2 Comments
Farid BOUSSAOUD
on 3 Apr 2024
Voss
on 3 Apr 2024
You're welcome!
Changing settings may be the best way to prevent the problem for files acquired in the future, but I'll leave my answer here since it may be useful for fixing files already acquired.
Categories
Find more on Spreadsheets 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!