I have an .csv
file made in Excel and that Excel uses ;
as delimiter. I don't like that, but I cannot change it.
So I have to accept it.
I want to read that .csv
file in GNU Octave
, but I can't really do it because the float numbers inside the .csv
file is separated with ,
e.g 15,25
and not separated with .
e.g 15.25
because in Excel, it assumes that 15.25
is a text string and 15,25
is a number. Yes, I know, it's weird.
If I change all ,
to .
in my .csv
file, then I can read the .csv
file with dlmread
or csvread
. But in this case, I don't want to change ,
to .
because that's a standard Excel configuration.
So my question is:
If you have a .csv
file were the float numbers are displayed with ,
. How can you read that .csv
file in GNU Octave
then?
CodePudding user response:
Sample file
i1;i2;i3
1,234;34,134;5,987
3,14;6,96;85,05
Script
clearvars
clc
nrows = 2;
ncolumns = 3;
data = textscan (fopen("data.csv", 'r'), "%s", "Delimiter", ";", "HeaderLines", 1);
data = cell2mat(data);
data = str2double(strrep(data,',','.'));
data = reshape(data, ncolumns, nrows); % elements are accessed in column-major order
data = transpose(data)
Logic
- We read the contents of the file as strings separated by
;
. - We replace the
,
present in the strings with.
. - Convert the strings to doubles.
- The data is reshaped to a matrix.
References
CodePudding user response:
For octave specifically, here is a one-liner solution.
str2double( strrep( csv2cell( 'testo.csv', ';' ), ',', '.' ) )
Requires the io
pkg to be loaded, for the csv2cell
function.