Skip to content

Commit 439a983

Browse files
committed
memory improvements csv read
1 parent c80ff28 commit 439a983

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

lexica/m/csv/csvimport.m

+18-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
function varargout = csvimport( fileName, varargin )
22
% CSVIMPORT reads the specified CSV file and stores the contents in a cell array or matrix
3+
% edited by Stijn Goossens to bump less frequent against memory issues
34
%
45
% The file can contain any combination of text & numeric values. Output data format will vary
56
% depending on the exact composition of the file data.
@@ -183,6 +184,7 @@
183184

184185
%Read first line and determine number of columns in data
185186
rowData = fgetl( fid );
187+
templine=rowData; % added by goosst
186188
rowData = regexp( rowData, p.delimiter, 'split' );
187189
nCols = numel( rowData );
188190

@@ -229,8 +231,22 @@
229231
error( 'csvimport:FileQueryError', 'FTELL on file ''%s'' failed.\nError Message: %s', ...
230232
fileName, msg );
231233
end
232-
data = fread( fid );
233-
nLines = numel( find( data == sprintf( '\n' ) ) ) + 1;
234+
235+
% less memory consuming way to get number of lines
236+
237+
% original: fread gives me a lot of out of memory complaints when reading larger csv files
238+
% data = fread( fid);
239+
% nLines = numel( find( data == sprintf( '\n' ) ) ) + 1;
240+
241+
%new addition:
242+
lines=1;
243+
while ischar(templine)
244+
templine = fgetl(fid);
245+
lines=lines+1;
246+
end
247+
nLines=lines-1;
248+
249+
234250
%Reposition file position indicator to beginning of second line
235251
if fseek( fid, pos, 'bof' ) ~= 0
236252
msg = ferror( fid );

0 commit comments

Comments
 (0)