分享

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

 美丽人生1991 2018-01-05

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);

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多