File Exchange

image thumbnail

dlmcell

version 1.3.0.1 (2.26 KB) by Roland Pfister
A cell array is written to a delimited output file, incl. options for appending & custom delimiters.

20 Downloads

Updated 13 Feb 2019

View License

Editor's Note: This file was selected as MATLAB Central Pick of the Week

This submission works similar as Sylvain Fiedlers / Rob Kohrs "cell2csv.m". Thus, any cell array containing numbers and/or strings can be written to an output file.

dlmcell.m, however, has two main advantages:

(1) It is possible to append the cell array to an existing file.

(2) Even numbers or words that are stored as <1,1> cell within the cell array can be read.

Cite As

Roland Pfister (2019). dlmcell (https://www.mathworks.com/matlabcentral/fileexchange/25387-dlmcell), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (74)

Since I can't edit my previous comment, I'm putting this here. You could also change where disp() is used for errors and to use the builtin function: error(). Then remove the return statements that follow.

I made a few edits to the original script including changes based on the comments of Frederik (27 Jan 2014) and Gabriel Vargas (8 Jul 2016). I changed what was line 87 from:
if size(cell_array{i,j},1) == 1 && size(cell_array{i,j},1) == 1 to if size(cell_array{i,j},1) == 1 && size(cell_array{i,j},2) == 1.

For simplicity, I'm just going to copy the whole thing here (line numbers have changed).

function dlmcell(file,cell_array,varargin)
%% <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> %%
% <><><><><> dlmcell - Write Cell Array to Text File <><><><><> %
% <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> %
% Version: 1.3.0.0 %
% (c) Roland Pfister %
% roland_pfister@t-online.de %
%...with many thanks to George Papazafeiropoulos for his corrections and %
%improvements. Also, Includes edits beased on the comments of Frederik, %
%Gabriel Vargas, and Andrew Ferrell. %
% 1. Synopsis %
% %
% A single cell array is written to an output file. Cells may consist of %
% any combination of (a) numbers, (b) letters, or (c) words. The inputs %
% are as follows: %
% %
% - file The output filename (string). %
% - cell_array The cell array to be written. %
% - delimiter Delimiter symbol, e.g. ',' (optional; %
% default: tab ('\t'}). %
% - append '-a' for appending the content to the %
% output file (optional). %
% %
% 2. Example %
% %
% mycell = {'Numbers', 'Letters', 'Words','More Words'; ... %
% 1, 'A', 'Apple', {'Apricot'}; ... %
% 2, 'B', 'Banana', {'Blueberry'}; ... %
% 3, 'C', 'Cherry', {'Cranberry'}; }; %
% dlmcell('mytext.txt',mycell); %
% %
% <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> %
%% Check input arguments
if nargin < 2
disp('Error - Give at least two input arguments!');
return;
elseif nargin > 4
disp('Error - Do not give more than 4 input arguments!');
return;
end
if ~ischar(file)
disp(['Error - File input has to be a string (e.g. ' ...
char(39) 'output.txt' char(39) '!']);
return;
end
if ~iscell(cell_array)
disp('Error - Input cell_array not of the type "cell"!');
return;
end
delimiter = '\t';
append = 'w';
if nargin > 2
for i = 1:size(varargin,2)
if strcmp('-a',varargin{1,i}) == 1
append = 'a';
else
delimiter = varargin{1,i};
end
end
end
%% Open output file and prepare output array.
output_file = fopen(file,append);
output = cell(size(cell_array,1),size(cell_array,2));
%% Evaluate and write input array.
for i = 1:size(cell_array,1)
for j = 1:size(cell_array,2)
if numel(cell_array{i,j}) == 0
output{i,j} = '';
% Check whether the content of cell i,j is
% numeric and convert numbers to strings.
elseif isnumeric(cell_array{i,j}) || islogical(cell_array{i,j})
output{i,j} = num2str(cell_array{i,j}(1,1));
% Check whether the content of cell i,j is another cell (e.g. a
% string of length > 1 that was stored as cell. If cell sizes
% equal [1,1], convert numbers and char-cells to strings.
%
% Note that any other cells-within-the-cell will produce errors
% or wrong results.
elseif iscell(cell_array{i,j})
if size(cell_array{i,j},1) == 1 && size(cell_array{i,j},2) == 1
if isnumeric(cell_array{i,j}{1,1}) || islogical(cell_array{i,j}{1,1})
output{i,j} = num2str(cell_array{i,j}{1,1}(1,1));
elseif ischar(cell_array{i,j}{1,1}) || isstring(cell_array{i,j}{1,1})
output{i,j} = cell_array{i,j}{1,1};
elseif isdatetime(cell_array{i,j}{1,1})
output{i,j} = datestr(cell_array{i,j}{1,1});
end
end
elseif ischar(cell_array{i,j}) || isstring(cell_array{i,j})
output{i,j} = cell_array{i,j};
elseif isdatetime(cell_array{i,j})
output{i,j} = datestr(cell_array{i,j});
end
% Cell i,j is written to the output file. A delimiter is appended for
% all but the last element of each row. At the end of a row, a newline
% is written to the output file.
if j < size(cell_array,2)
fprintf(output_file,['%s',delimiter],output{i,j});
else
fprintf(output_file,'%s\r\n',output{i,j});
end
end
end
%% Close output file.
fclose(output_file);
end

it works good thanks...but how ican add more data to the same file afterwards??

aaronb

Works well, thanks!

How to install and use it on Linux?

Leo

excellent!

is it be able to store a cell within the cell array with a 1xn Dimension?

Donghee Min

Thanks a lot!

linying lu

PP

very good small tool

to output datetime as a string use the function datestr(datetime,formatOut), then use dlmcell and it will be compatible with matlab datetime.

great piece of code, definitely helped me solve some issues. it would be interesting if this could handle datetime and print it as a text

Works perfectly! Thanks :)

Arash

It works. Nice Job, thank you.

rmc

Jan Motl

It just works. Thanks!

Jothi

Its word great and save more time.

Nice work.

Thanks.

Scott

Sorry for the additional post (first time posting and it looks like I can't delete posts and when you select the stars to rate the file it automatically posts!)

Anyways, ignore my comments below. I quickly realized I should just make a one cell array not nested arrays using square brackets instead of curly:

cell_array=[cells cell_nums];
dlmcell('mytext.txt',cell_array);

With this correction it appears to work great

Scott

Scott

*Made a correction to my demo code*

If someone following this can help me I think I might cry.

With the following demo code dlmcell only puts the first 3x1 cell array into the text file and ignores the rest.

cells={'---';'aa';'boohoo hoo'};
nums=[1,2,3;4,5,6;7,8,9];
cell_nums=num2cell(nums);
cell_array={cells cell_nums};
dlmcell('mytext.txt',cell_array{:});

I need the text output to be like so:
--- 1 2 3
aa 4 5 6
boohoo hoo 7 8 9

Any ideas?
Thanks!

Scott

If someone following this can help me I think I might cry.

With the following demo code dlmcell only puts the first 3x1 cell array into the text file and ignores the rest.

cells={'---';'aa';'boohoo hoo'};
nums=[1,2,3;4,5,6;7,8,9];
cell_nums=num2cell(nums);
cell_array={a c};
dlmcell('mytext.txt',cell_array);

I need the text output to be like so:
--- 1 2 3
aa 4 5 6
boohoo hoo 7 8 9

Any ideas?
Thanks!

Pw

You just saved me soooo much time. Thank you!

Mamun

nice work!!! kudos

Irene

Fredrik

I've altered the code somewhat since the program doesn't handle cell arrays containing strings. (There's just an else option missing)

so lines 86-93 becomes:
elseif iscell(cell_array{i,j})
if size(cell_array{i,j},1) == 1 && size(cell_array{i,j},1) == 1
if isnumeric(cell_array{i,j}{1,1})
output{i,j} = num2str(cell_array{i,j}{1,1}(1,1));
elseif ischar(cell_array{i,j}{1,1})
output{i,j} = cell_array{i,j}{1,1};
end;

else
output{i,j} = cell_array{i,j}{1,1};
end;

Frosch

Thank you for this nice piece of code. I had the same problem as George with the \t delimiter and changed it in a similar way, unfortunately before reading his comment ;-)Nevertheless this file saved me a lot of work!

David

Needed to output a cell to .csv file. However when I used the "cell2csv" command from the file exchange, newline characters were not recognized by notepad when I opened the csv file. The newline characters were recognized by Excel 2010 though.

MATLAB commands:
myCell = {'a';'0,1,4,4,-20,-30';'test string'}
cell2csv('cell2csv_test.csv',myCell)

opening cell2csv_test.csv in notepad:
a0,1,4,4,-20,-30test string

However this function did output to a .csv file with newline characters recognized by notepad. It's not a huge deal, but I was trying to make a csv file that matched a template at work *exactly* (with newlines recognizable by notepad).

MATLAB commands:
myCell = {'a';'0,1,4,4,-20,-30';'test string'}
dlmcell('dlmcell_test.csv',myCell)

opening dlmcell_test.csv in notepad:
a
0,1,4,4,-20,-30
test string

I changed the lines 96 to 104 which were the following:

% Cell i,j is written to the output file. A delimiter is appended
% for all but the last element of each row.
fprintf(output_file,'%s',output{i,j});
if j ~= size(cell_array,2)
fprintf(output_file,'%s',delimiter);
end
end;
% At the end of a row, a newline is written to the output file.
fprintf(output_file,'\r\n');

into the following:

% Cell i,j is written to the output file. A delimiter is appended for
% all but the last element of each row. At the end of a row, a newline
% is written to the output file.
if j < size(cell_array,2)
fprintf(output_file,['%s',delimiter],output{i,j});
else
fprintf(output_file,'%s\r\n',output{i,j});
end
end;

and it runs fine. The newline written to the output file at the end of each line was erroneously left outside the for j = 1:size(cell_array,2) loop. In addition the delimiter and the '%s' strings were concatenated into a single string to provide input for the fprintf function.

Yuri K

Why cannot you fix this annoying bug with \t?

Tony

Uni A

Thanks for the code. I am facing a problem. Basically, I have a huge .mat file containing a list of urls. This i convert to cell format and now each row is a url, and there are around 300k rows. Now when I try to write this huge cell into a text file, it stops after around 4000 lines and says index exceeds error.

Anu suggestions please? This is kinda urgent.

Ricardo

works fine. thanks so much

Robin

Great function! Love it!
Is there a way to add any formatting to the text? For example changing the font style (e.g., bold, oblique etc.) and the color?
Many thanks!

This utility doesn't work consistently for me. Specific problems:

1) Documentation states that file name is taken as the file specification. However, the function occasionally generates errors like the following:

------------------------------
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.

Error in dlmcell (line 98)
fprintf(output_file,'%s',output{i,j});
------------------------------

fprintf() requires a file handle as first argument. I'll therefore have to dig into this F/E function & possibly modify.

2) This function doesn't return any values, even on error. Instead, it prints error messages at the command-line & returns normally. This is poor programming practice & makes it inconvenient to deploy within another function where error-detection must be handled programmatically.

One star subtracted for each of these problems.

Mango

Great work, absolutely phenomenal for what I'm trying to do. I have one problem though. In my cell array that's being printed, one of my columns has a comma in it i.e. "contract 5,000 bushels" turns into "contract 5" "000 bushels" Is there a way to fix this?

Mango

Absolutely phenomenal. Only thing I could ask for would be a way to use something similar to the format %q that is available from textscan.

Nice!

I encountered the same problem as sohrab, with \t printed in the file rather than tabs. I fixed it by replacing row 100 from
>>fprintf(output_file,'%s',delimiter);
to just
>>fprintf(output_file,delimiter);

Thanks for an excellent file!

sohrab

\t is printed except of doing tab! what should i do?

Alex

sharsad

Cool function. But using dlmcell I could only write the first element of my cell.
My cell is in the following format;
C =
[1x5 double] [0.1962] [1x3 double] [2x3 double];
I could only write the first element of each cell content unless I need to type all the contents of my cell using the curly brace format.
Can anyone help me with this?your reply will be much appreciated

Matlab2010

excellent.

daisy

Great function! We've had problem with cell2csv, thanks to dlmcell that solves our trouble!

Evan

This is an extremely useful script (thank you!) but I'm running into a little problem executing from Linux - slashes are appended between the fields before an after the delimiter - any ideas?

Example output text:
\Filename\,\StartDate\,\EndDate\,\Number of Measurements\

Great function, works awesome, was clearly missing as a built-in. Well done. (gave it 5 stars, but it's not showing up in Chrome??)

Jane T

Like Matt I was having a problem with the '\t' appearing in the file. I'm running 2011a in Windows 7.
I changed line 100 to read 'fprintf(output_file,delimiter);'

Michael

so awesome!

Seth

Truc Phan

works great! thanks

Its OK. I had a problem...could be a Mac thing. Instead of making a new line in the file, the text appeared in the file as "Hello\n", that is the special characters appeared in the file.
To get around the problem I changed the program to read:
fprintf(fid,'%s\n',astring)
That is, I put the special character directly in the second parameter. Then it created a new line.

Boris

Very useful! Works perfectly! Thanks.

Ivan Brezani

perfect, thanks!

This function is good, thanks, man!

Fabio Gori

It makes my life simpler!

Russ

Yonatan Cal

Thanks for this file!

Jeff Evans

works perfectly! just as described.

Updates

1.3.0.1

Includes the latest edits as suggested and implemented by Andrew Ferrell on Feb. 9, 2019.

1.3.0.0

Includes the latest edits as suggested and implemented by Andrew Ferrell on Feb. 9, 2019.

1.2.0.0

Bugfixes and corrections.

1.1.0.0

Little bugfix concerning %-signs.

MATLAB Release Compatibility
Created with R2009a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Discover Live Editor

Create scripts with code, output, and formatted text in a single executable document.


Learn About Live Editor