File Exchange

image thumbnail

Cell Array to CSV-file [cell2csv.m]

version 1.1 (1.89 KB) by

Writes a cell array into a comma separated values text file (*.csv)

4.7907
43 Ratings

133 Downloads

Updated

View License

This function writes a cell array into a CSV-file.
It works with empty cells, numeric, char, string and logical cells. One array can contain all of them, but only one value per cell.

CSV-files can then be read by Excel, so you don't need DDE or ActiveX.

Comments and Ratings (50)

eme

eme (view profile)

I use this function regularly and it always worked great. However now I experience some issues. I want to save cells of different types to a txt file, which works well when I open the resulting text file in matlab. If however, I open the file outside matlab (e.g. with notepad) the rows of the cell are not separated as individual rows in the txt file.

An example:

I want this:
Header1, Header 2, Header 3
Data1, 999999, 888888
Data2, 77777,66666

but the resulting text file looks like this
Header1, Header 2, Header 3, Data1, 999999, 888888, Data2, 77777, 66666

Any ideas? Thanks a lot

Geng Deng

This function doesn't work for cells with commas. For example, if I run

out = {'ReadMe, Inc.', 'ReadMe2, LLC'};
cell2csv( '\test.csv',out);

the resulting csv fille would have four cells, instead of two. Does anyone know how to resolve this problem?

Vahid

Vahid (view profile)

Hang Dong

so effective!

Kahfi Gunardi

THANK YOU SO MUCH!

Flo Hem

Good and simple, but a bit slow.
Saved me the hassle of duplicating the code.

It can be enhanced by using 'W' instead of 'w' in fopen and is MUCH faster! Autoflush is very slow!

Check out this link: http://blogs.mathworks.com/loren/2006/04/19/high-performance-file-io/

This was not working for me for 2d cell arrays of varying column sizes. To fix this, I changed the fprintf to the following:

try
fprintf(datei, '%s', var{1,:});
catch

end

e.g. a 3d cell array

Zac Giles

Zac Giles (view profile)

Jan Berling

rd2047

rd2047 (view profile)

Ricardo

Just FYI:

I had a problem with this script when my cell array had a row with strings: all the values were written as 'NA', supposedly because they didn't verify the conditions from all the elseif's of StringX(x).

If I deleted the last else it would give me an error: "Error using sprintf
Function is not defined for 'cell' inputs."

So I changed the last else from

else
x = 'NA';
to:

else
x = char(x);

And it worked. No more 'NA'.

Thank you for your script. Good work ;)

Charlotte

Alex

Alex (view profile)

Jerry

Jerry (view profile)

I modified according to Justin and Jan's suggestions. And also added support for row vector. It is much faster now. See the updated file at http://www.mathworks.com/matlabcentral/fileexchange/47055-cell2csv-m

credits go to Sylvain.

Justin Su

A very convenient code. However, it is a little bit slow for saving large tables.
Jan Simon's suggestion is very helpful. Another way to further improve its speed is to bundle the output to fprintf() as much as possible. For example, write a whole line at one call rather than call fprintf() for each cell.
These two tweaks can reduce the excution time by >60%.

Alireza

Alireza (view profile)

Jan Simon

Jan Simon (view profile)

This function has a large potential for improvements:
"var = eval(['cellArray{z,s}']);" could be replaced by the much faster and nicer "v = cellArray{z,s};".
"if size(var, 1) == 0" does not catch [1x0] arrays, while "isempty(v)" would.

Checking the success of FOPEN is strongly recommended to avoid a strange behaviour.

The documentation is sufficient and the function works as advertised.

Igor

Igor (view profile)

Nice function, but a tiny check for a proper result from fopen() might be nice (just for user to get better error messages).

geieraffe

is there a Version with "append", like Manish Mittal wrote on 15 Sep 2005?
Can't find it!
But would be great! I need exact this, ...just with an "append" option

Pearl

Pearl (view profile)

Wouter

Wouter (view profile)

csv2cell can be done by using a combination of uigetfile and textscan.

Robert

Robert (view profile)

Nice m-script. Here a diff to account for cellstr contents and empty cells:
diff cell2csv.m cell2csv_orig.m
70,73c70,72
< if isempty(var)
< continue
< end
<
---
> % OUTPUT value
> fprintf(datei, '%s', var);
>
75c74
< if s ~= 1 %size(cellArray, 2)
---
> if s ~= size(cellArray, 2)
78,86d76
<
< % OUTPUT value
< if ischar(var)
< fprintf(datei, '%s', var);
< elseif iscellstr(var)
< fprintf(datei, '%s', var{1});
< end
<
<

Irene

Irene (view profile)

Thanks; just used it to convert a 1048576x10 cell array to csv, took about 5 hours but didn't crash.

Ivan Brezani

Anastasia

Thanks for the great script, just a note, I modified the line 56 to allow for output with CR/LF termination as required by some windows and visual basic programs.

fprintf(datei,'\r\n');

It may be worth adding as an option.

helen chen

so far it's working fine:) btw, you could use the textscan function in matlab 7 to convert csv to cell array

R B

This is apparently an older version of another cell2cvs on mathworks.com and should be removed

R B

Buggy. Breaks fprintf in some cases

Wouter Rogiest

I am using this in all my MATLAB code --thanx! but I can't help wondering if anyone has made a csv2cell ?

Joe Lotz

Very help, thanks alot for sharing!

Kevin Keegan

Is there a code for a reverse version of this -- csv2cell ? I've seen C versions but not Matlab ones -- having a bit of trouble writing one myself.
Thanks -- Kevin

Chris Curtis

This is a big help. I'm having a hard time wrapping my mind around cell arrays and this is perfect. Very flexible, simple, and user-friendly. Thanks!

Mike B

As per the comments above this is excellent. I'm using it just to generate text file output, so its perfect.

Manish Mittal

Here is another version of the same file with append, overwrite etc options. Also the delimeter issue is fixed

function cell2csv(filename,cellArray,delimiter,mode)
% Writes cell array content into a *.csv file.
%
% CELL2CSV(filename,cellArray,delimiter)
%
% filename = Name of the file to save. [ i.e. 'text.csv' ]
% cellarray = Name of the Cell Array where the data is in
% delimiter = seperating sign, normally:',' (it's default)
% mode = specifies the mode of opening the file. See fopen() for a detailed
% list (default is overwrite i.e. 'w')
%
% by Sylvain Fiedler, KA, 2004
% modified by Rob Kohr, Rutgers, 2005 - changed to english and fixed delimiter
if nargin<3
delimiter = ',';
end
if nargin<4
mode = 'w';
end

datei = fopen(filename,mode);
for z=1:size(cellArray,1)
for s=1:size(cellArray,2)

var = eval(['cellArray{z,s}']);

if size(var,1) == 0
var = '';
end

if isnumeric(var) == 1
var = num2str(var);
end

fprintf(datei,var);

if s ~= size(cellArray,2)
fprintf(datei,[delimiter]);
end
end
fprintf(datei,'\n');
end
fclose(datei);

Miklos Argyelan

P L

In addition to R k's comment, change lines 32-34 to:

if s ~= size(cellArray,2)
fprintf(datei, trennZeichen);
end

R K

since it is a csv it should be commas as the seperator.

if nargin<3,trennZeichen = ',';end

C T

Marcelo Zeri

Excelent, exactly what I need.

Sergio Lucero

Great. Also needs to accept a different separator, so besides line 32 it needs to change line 12 to
if nargin<3,trennZeichen = ';';end

Juan F. Navas

It is simple, it is effective, and not only can write csv, it can read formats created by the user changing the "separator". Needs and adjustement at line 32:
fprintf(datei,trennZeichen);

Ted Skolnick

Simple and effective.

Updates

1.1

Added the choice of the decimal separator

Improved file to wirk with Excel 97,2000 oder alternatively with Excel 2003.
Microsoft changed the default seperator, so now when Excel Version is > 2003, it is taken care of.

adapted separator for OfficeXP

Updated to work easier with OfficeXP.

MATLAB Release
MATLAB 7.8 (R2009a)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Win prizes and improve your MATLAB skills

Play today