Error using fprintf when copying cell content into a text file

1 vue (au cours des 30 derniers jours)
Ahmad Fakih
Ahmad Fakih le 12 Déc 2019
Modifié(e) : dpb le 13 Déc 2019
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 commentaires
Rik
Rik le 13 Déc 2019
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.
Ahmad Fakih
Ahmad Fakih le 13 Déc 2019
@Rik the the cell is linked below. Its called R1. It contains many 1 by 1 cells only.

Connectez-vous pour commenter.

Réponse acceptée

Rik
Rik le 13 Déc 2019
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);

Plus de réponses (1)

dpb
dpb le 13 Déc 2019
Modifié(e) : dpb le 13 Déc 2019
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.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by