print elements of cell array to file

Hi there,
I have the following cell array.
f={[1;2;3;4] [5;6;7;8;9;10;11] [12;13;14;15;16;17;18;19;20;21;22;23]}
I want the output to be written to a file and it should look like....
set1
1, 2, 3, 4
set2
5, 6, 7, 8, 9
10, 11
set3
12, 13, 14, 15, 16
17, 18, 19, 20, 21
22, 23
as you can see the set number refers to the row number of cell array {f}. Also when printing the number to file, each line can have a maximum of 5 values so if you have more than 5, it continues from next line.
Thanks for your help in advance. Let me know if further clarification is needed.
Mohan

 Akzeptierte Antwort

Sathish Kumar
Sathish Kumar am 3 Apr. 2013

0 Stimmen

Hai, try the one below....any doubts on the steps just comment on it....
f={[1;2;3;4] [5;6;7;8;9;10;11] [12;13;14;15;16;17;18;19;20;21;22;23]};
s=size(f,2);
myfile=fopen('filename.txt','w');
for i=1:3
a=cell2mat(f(i));
fprintf(myfile,'set%d\n',i);
sa=size(a,1);
for j=1:sa
fprintf(myfile,'%d ',a(j));
if mod(j,5)==0
fprintf(myfile,'\n');
end
fprintf(myfile,'\n');
end
fclose(myfile);
end

3 Kommentare

mohan
mohan am 3 Apr. 2013
Hi Sathish
I tried your code, it seems to be complaining at line fprintf(myfile,'set%d\n',i). Matlab says '??? Error using ==> fprintf Invalid file identifier. Use fopen to generate a valid file identifier.'. I've tried different file identifiers but same message.
Thanks
Mohan
Hi
I got it to work by modifying your code as shown below. But I'm struggling to get it to write only 5 variables on a line. Also this modified code prints a comma even for the last variable as well, which is not required.
f={[1;2;3;4] [5;6;7;8;9;10;11] [12;13;14;15;16;17;18;19;20;21;22;23]};
s=size(f,2);
fileID=fopen('filename.txt','w');
for i=1:3
a=cell2mat(f(i));
fprintf(fileID,'set%d\n',i);
sa=size(a,1);
% for j=1:sa
fprintf(fileID,'%d, ',f{i});
% if mod(j,5)==0
% fprintf(fileID,'\n');
% end
fprintf(fileID,'\n');
% end
end
fclose(fileID);
Mohan
here is the correct code for anyone interested.....
f={[1;2;3;4] [5;6;7;8;9;10;11] [12;13;14;15;16;17;18;19;20;21;22;23]};
s=size(f,2);
fileID=fopen('filename.txt','w');
for i=1:s
a=cell2mat(f(i));
fprintf(fileID,'set%d\n',i);
sa=size(a,1);
for j=1:sa
if (j ~= sa)
fprintf(fileID,'%d,',a(j));
else
fprintf(fileID,'%d',a(j));
end
if mod(j,5)==0
fprintf(fileID,'\n');
end
end
fprintf(fileID,'\n');
end
fclose(fileID);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Data Import and Analysis finden Sie in Hilfe-Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by