How do I save a cell array that contains both strings and numbers to an ASCII file in MATLAB?

66 views (last 30 days)
I have a cell array that contains both strings and numbers. I have tried to save the data to an ASCII file but I am unable to do so using SAVE or DLMWRITE.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 18 Oct 2013
The ability to save a cell array with both strings and numbers using a single function is not available in MATLAB. To work around this issue, refer to the examples below.
Run the following code to create an example mixed data type cell matrix:
ex1 = {'a' 1 12 123; 'ab' 4 5 6; 'abc' 7 8 9}
1. Using CELLFUN, you can create a function to iterate through each element of the cell and convert it to the appropriate data type as well as append a variable number of spaces. In this example, you can create a function that will convert all the data into strings.
Place the attached MATLAB files, 'ex_func.m' and 'ex_func2.m' in your directory. Using the following code should create the same number of spacing for each entry, which will allow you to use the CELL2MAT function to convert the cell array to a char matrix.
ex2 = cellfun(@ex_func,ex1,'UniformOutput',0);
size_ex2 = cellfun(@length,ex2,'UniformOutput',0);
str_length = max(max(cell2mat(size_ex2)));
ex3 = cellfun(@(x) ex_func2(x,str_length),ex2,'uniformoutput',0)
From the char matrix, you can use the FPRINTF function to properly output strings to a text file, as shown below:
ex4 = cell2mat(ex3);
fid = fopen('mydata.txt','wt');
for i = 1:size(ex4,1)
fprintf(fid,'%s %s %s %s\n',ex4(i,1:3),ex4(i,4:6),ex4(i,7:9),ex4(i,10:12));
end
fclose(fid);
2. If Microsoft Excel is available for use, you can use the XLSWRITE function to export the data to a worksheet. Then using the 'Save As' function from the 'File' menu, you can save the worksheet to a text file.
xlswrite('mydata.xls',ex1);
  1 Comment
Brad
Brad on 15 Jan 2014
Question: If using the above approach to solve the problem of saving a cell array that contains both strings and numbers to an ASCII file, is there a way to left justify the text going to mydata.txt?

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!