How do I write a cell array of strings to a file using DLMWRITE or CSVWRITE functions in MATLAB?

조회 수: 9 (최근 30일)
I would like to write my cell array out to a delimited file, but DLMWRITE and CSVWRITE do not support it.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2010년 1월 14일
This change has been incorporated into the documentation in MATLAB 7.9 (R2009b). For previous releases, read below for any additional information:
The ability to save a cell array of strings to a text file with one function is not available in MATLAB but can be implemented in a number of methods. You will need to use low-level file I/O routines to achieve this. Depending on whether you have stored numbers or text in your cell array, you may need to modify the code below to be specific for your cell array:
fid=fopen('myFile.csv','wt');
x={'sin','cos','tan','log','exp'};
[rows,cols]=size(x)
for i=1:rows
fprintf(fid,'%s,',x{i,1:end-1})
fprintf(fid,'%s\n',x{i,end})
end
fclose(fid);
The same may be achieved without a loop, but using string and cell manipulation functions available in MATLAB:
fid=fopen('myFile.csv','wt');
x={'sin','cos','tan','log','exp'};
csvFun = @(str)sprintf('%s,',str);
xchar = cellfun(csvFun, x, 'UniformOutput', false);
xchar = strcat(xchar{:});
xchar = strcat(xchar(1:end-1),'\n');
fprintf(fid,xchar)
fclose(fid);
If you do have to modify any of the above code, some functions that may be helpful are: ISNAN, ISNUMERIC, ISCHAR, FPRINTF, FOPEN and FCLOSE.
You can find more information about each of these functions in the documentation. For example, to read more on ISNAN, type the following at the MATLAB command prompt:
doc isnan
or
help isnan
  댓글 수: 1
Rini Varghese
Rini Varghese 2017년 5월 27일
A simpler way perhaps is to set the delimiter to ''. For example: x = {'sin';'cos'}; y = cell2mat(x); dlmwrite('myfile',y,''); Note that x is separated by ; instead of , Hope this helps!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

제품

Community Treasure Hunt

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

Start Hunting!

Translated by