3

When I tried using xlswrite for a cell array 4X10 or so with strings of different lengths in each element, MATLAB returned this error:

Error using xlswrite (line 188)
An error occurred on data export in CSV format.

Caused by:
    Error using dlmwrite (line 118)
    The input cell array cannot be converted to a matrix.

What I boiled it down to is that somewhere in the "dlmwrite" function that is called by "xlswrite", it calls "cell2mat" which will concatenate the elements of my cell array to a character array. However, it will concatenate the elements vertically and horizontally, and it is not possible to concatenate character elements vertically if they do not have the same length. You will end up with an array on inconsistent dimensions. For example,

If I have 'abcdef' and 'abc', concatenating them vertically would give:

abcdef

abc

The first row has a length of 6, and the second row has a length of 3, which does not make logical sense if you're talking about a matrix, which should be 2X6 in this case.

Does anybody know a workaround for this? I'm pretty frustrated with this glitch in MATLAB.

David S
  • 45
  • 1
  • 6
  • can you post the data that you try to write? – Serg Dec 09 '12 at 04:35
  • a = {'$','gsqtmpiv','lsso';'gsqqmwwmsr','efwxvegxmsr','gpsgo';'hexyq','tst','vyffiv';'pek','geqive','xerkmivw';'tvigsppyhih','fewmexih','vywxmgepp}'; – David S Dec 09 '12 at 05:40
  • 1
    The simple woraround would be to padd the data yourself. Furthermore note that your `a` does not appear to be properly defined and that it is best to include the minimal example in the question. – Dennis Jaheruddin Dec 10 '12 at 15:05

1 Answers1

2

I do not get your error - at least with my version of the input. There is an error in your 'a', but I guess that is just in the comment and not in your actual code.

Maybe the error got fixed? I am using 2012a.

Anyway; you can use the suggested workaround. It is just a single line of code.

% here are your data
a = {'$','gsqtmpiv','lsso';...
    'gsqqmwwmsr','efwxvegxmsr','gpsgo';...
    'hexyq','tst','vyffiv';...
    'pek','geqive','xerkmivw';...
    'tvigsppyhih','fewmexih','vywxmge'};

% this works fine in 2012a
xlswrite('blah.xls',b)

% but using dlmwrite directly fails
% like you described
try
    dlmwrite('test.txt', a)
catch ME
    disp(ME.message)
end

% so instead use the suggested work-around:
b = cellfun(@(s) sprintf('%-12s', s), a, 'UniformOutput', false);
% and dlmwrite will no longer fail
dlmwrite('test.txt', b)

You need to know the max length of string (11 in your testdata) and use that in the formatting string

'%12s' 

gives a max length of 12.

The problem with that is that if you use it with xlswrite, you will have spaces in the strings. They are invisible if you use the

'%-12s' 

formatting, so unless you use the strings for further processing it may be ok?