Error using fprintf when copying cell content into a text file
조회 수: 1 (최근 30일)
이전 댓글 표시
I'm trying to copy the content of the following cell into a text file.
I'm using the following code:
[maxrow, maxcolumn]=size(MyCell);
id = fopen('filename.txt','w+t');
if id<0
error('could not open file');
end
for ro =1:maxrow
for co =1:maxcolumn
fprintf(id,'%10s',MyCell{ro,co});
end
fprintf('\n')
end
fclose(id)
But I'm getting this error:
"Error using fprintf
Function is not defined for 'cell' inputs."
Any help?
Thanks!
댓글 수: 5
Rik
2019년 12월 13일
Replace MyCell{ro,co} with something that makes sure you access the contents. From your screenshot it is difficult to tell what that syntax should be.
채택된 답변
Rik
2019년 12월 13일
The code below works, but it is probably better to define your FormatSpec in such a way that you can print your data line by line .
S=load('MATLAB Cell to Text.mat');MyCell=S.R1;
[maxrow, maxcolumn]=size(MyCell);
id = fopen('filename.txt','w+t');
if id<0
error('could not open file');
end
for ro =1:maxrow
for co =1:maxcolumn
data=MyCell{ro,co};
if isa(data,'cell')
%assume a nested cell with a char array
fprintf(id,'%10s',data{1});
else
%assume a numeric type
fprintf(id,'%.2f',data);
end
end
fprintf(id,'\n');
end
fclose(id);
추가 답변 (1개)
dpb
2019년 12월 13일
편집: dpb
2019년 12월 13일
Having data helps...to achieve the objective in the easiest way w/o writecell, use the intermediary of converting to a table...
writetable(cell2table(R1),'celldata.txt')
results in the file containing...
>> tR1=cell2table(R1);
>> writetable(tR1(1:10,:),'celldat.txt')
>> type celldat.txt
R11,R12,R13,R14,R15,R16,R17
Link=,1, DOF=U1 Fixed=No NonLinear=Yes TransKE=0 TransCE=0, Force=,NaN, Displ=,0.05
Link=,1, DOF=U1, Force=,NaN, Displ=,0.035
Link=,1, DOF=U1, Force=,NaN, Displ=,0.025
Link=,1, DOF=U1, Force=,NaN, Displ=,0.015
Link=,1, DOF=U1, Force=,NaN, Displ=,0.008
Link=,1, DOF=U1, Force=,NaN, Displ=,0.005
Link=,1, DOF=U1, Force=,NaN, Displ=,0.003
Link=,1, DOF=U1, Force=,NaN, Displ=,0.001
Link=,1, DOF=U1, Force=,NaN, Displ=,0.0005
Link=,1, DOF=U1, Force=,0, Displ=,0
>>
for a small section.
If there's intent and/or need to do something with the data other than just create a text file from it, it would probably be best to go back to the point at which the content was created and do something differently there -- probably when the data were read from their source as looks like was machine-created.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Annotations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!