MATLAB Answers

Error using fprintf when copying cell content into a text file

조회 수: 1(최근 30일)
Ahmad Fakih
Ahmad Fakih 12 Dec 2019
편집: dpb 13 Dec 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

표시 이전 댓글 수: 2
Ahmad Fakih
Ahmad Fakih 13 Dec 2019
I there anyway around this for the R2018a version? Apparently my large cell consists of many cells each containing one element only (all the small cells are basically 1x1). I wonder if there's a way to make it one big 2D cell.
Rik
Rik 13 Dec 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 13 Dec 2019
@Rik the the cell is linked below. Its called R1. It contains many 1 by 1 cells only.

로그인 to comment.

채택된 답변

Rik
Rik 13 Dec 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);

  댓글 수: 1

로그인 to comment.

추가 답변(1개)

dpb
dpb 13 Dec 2019
편집: dpb 13 Dec 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.

  댓글 수: 0

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by