@@ -66,6 +66,7 @@ function write(obj, fileName, varargin)
6666% default values of parameters
6767format = [];
6868writeHeader = ~isempty(obj .ColNames );
69+ rowNames = obj .RowNames ;
6970writeRowNames = ~isempty(obj .RowNames );
7071writeLevels = hasFactors(obj ) ;
7172sep = ' ' ;
@@ -106,6 +107,11 @@ function write(obj, fileName, varargin)
106107nRows = size(obj .Data , 1 );
107108nCols = size(obj .Data , 2 );
108109
110+ % if need to write row names without valid row names, ensure valid ones.
111+ if writeRowNames && isempty(rowNames )
112+ rowNames = createRowNames(obj );
113+ end
114+
109115% compute default format string for writing data, if not given as argument
110116if isempty(format )
111117 format = [' %g ' repmat(' %g ' , 1 , nCols - 1 ) ' \n ' ];
@@ -176,12 +182,8 @@ function write(obj, fileName, varargin)
176182end
177183
178184% add '%s ' in the beginning if missing
179- if nTokens ~= nCols + 1 && ~isempty(obj .RowNames )
180- % len = -1;
181- % for i = 1:nRows
182- % len = max(len, length(obj.rowNames{i}));
183- % end
184- len = max(cellfun(@length , obj .RowNames ));
185+ if nTokens ~= nCols + 1 && writeRowNames
186+ len = max(cellfun(@length , rowNames ));
185187 format = [' %-' int2str(len ) ' s ' format ];
186188end
187189
@@ -201,15 +203,16 @@ function write(obj, fileName, varargin)
201203
202204% write the header line
203205if writeHeader
204- % initialize first row with default tag
205- str = ' name' ;
206-
207206 % write the names of the columns, separated by spaces
208- for i = 1 : nCols
209- str = [str headerSep obj.ColNames{i }]; % #ok<AGROW>
210- end
207+ pattern = [' %s ' repmat([headerSep ' %s ' ], 1 , nCols - 1 ) ' \\ n' ];
208+ str = sprintf(pattern , obj.ColNames{: });
211209
212- str = [str ' \n ' ];
210+ % optionnally adds column name for row names
211+ if writeRowNames
212+ str = [' name' headerSep str ];
213+ end
214+
215+ % print header to file
213216 fprintf(f , str );
214217end
215218
@@ -218,7 +221,7 @@ function write(obj, fileName, varargin)
218221 % write data as numeric
219222 if writeRowNames
220223 for i = 1 : nRows
221- fprintf(f , format , obj.RowNames {i }, obj .Data(i , : ));
224+ fprintf(f , format , rowNames {i }, obj .Data(i , : ));
222225 end
223226 else
224227 for i = 1 : nRows
@@ -241,7 +244,7 @@ function write(obj, fileName, varargin)
241244
242245 % write current row
243246 if writeRowNames
244- fprintf(f , format , obj.RowNames {i }, data{: });
247+ fprintf(f , format , rowNames {i }, data{: });
245248 else
246249 fprintf(f , format , data{: });
247250 end
0 commit comments