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!