问题
After searching mathworks' website and here too I managed to find the code that is SUPPOSED to work for saving cell data to a text file... but every variation I found doesn't work. Here's my current code (and the one that has appeared the most here and on mathworks) - please help me figure out why it's not working for me...:
first attempt:
array = cell(1,10);
for i=1:10
array{i} = 'someText';
end
fid = fopen('file.txt', 'wt');
fprintf(fid, '%s\n', array);
fclose(fid);
Error:
Error using fprintf Function is 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 attempt:
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);
Error:
Error using fprintf Function is not defined for 'cell' inputs.
Error in saveToFile (line 12) fprintf(fileID,'%s\n' ,array{row,:});
I will spare you some other failed attempts.. these were the best I could find.. Any help will be greatly appreciated! :)
回答1:
The code below works for me fine:
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 by assigning the cell content in a variable of type CHAR.
回答2:
Alternatively, you could use strjoin to join a cell array 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);
来源:https://stackoverflow.com/questions/26125280/matlab-saving-cell-array-to-text-file