Matlab saves array cell to text file

After searching the mathworks website and here too, I was able to find code that SUPPOSED works to save cell data in a text file ... but every variation I found doesn't work. Here is my current code (and the one that showed up the most here and on mathworks) - please help me figure out why it doesn't work for me ...:

first try:

array = cell(1,10);
for i=1:10
    array{i} = 'someText';
end
fid = fopen('file.txt', 'wt');
fprintf(fid, '%s\n', array);
fclose(fid);

      

Mistake:

Error using fprintf Function not defined for "cell" inputs.

Error in saveToFile (line 11) fprintf (fid, '% s \ n', array);

So I specifically looked for one that is good for cell arrays (can be found here: http://www.mathworks.com/help/matlab/import_export/write-to-delimited-data-files.html )

Second try:

array = cell(1,10);
for i=1:10
    array{i} = 'someText';
end
fileID = fopen('celldata.dat','w');
[nrows,ncols] = size(array);
for row = 1:nrows
fprintf(fileID,'%s\n' ,array{row,:});
end
fclose(fileID);

      

Mistake:

Error using fprintf Function not defined for "cell" inputs.

Error in saveToFile (line 12) fprintf (fileID, '% s \ n', array {row ,:});

I will spare you other failed attempts. It was the best I could find. Any help would be greatly appreciated! :)

+3


source to share


2 answers


The code below works well for me:

array = cell(10,1);
for i=1:10
  array{i} = ['someText ' num2str(i)];
end
fileID = fopen('celldata.dat','w');
[nrows,ncols] = size(array);
for row = 1:nrows
    temp_str = array{row,:};
    fprintf(fileID ,'%s\n', temp_str);
end
fclose(fileID);

      



The main difference is the assignment of the cell contents to a CHAR variable.

0


source


Alternatively, you can use strjoin

to concatenate an array of cells into a string:



array = cell(1,10);
for i=1:10
    array{i} = 'someText';
end
line = strjoin(array)
fid = fopen('file.txt', 'wt');
fprintf(fid, '%s\n', line);
fclose(fid);

      

0


source







All Articles