2
votes

Dear stackoverflowers,

I'd like to create a .txt file using matlab. The content should be separated with tabs. It should have 3 columns, and the 3rd column should be filled with strings from a cell array. Let's say

A=[2; 3; 3;];
B=2*A;
C=cell(3,1);
C{1,1}='string1'; C{2,1}='string2'; C{3,1}='string3';

In the end, it should look like this:

    2  4  string1
    3  6  string2
    3  6  string3

I already found out, how to put the 2 matrices in a text file: dlmwrite('filename.txt', [A B], 'delimiter', '\t')

But how to append the content of the cell? It would be best, to have only the strings in the file, not the single quotes. I neither found a solution to this elsewhere, nor did I ask this somewhere else. I apprechiate all kinds of suggestions.

2
Use cprintf to generate a character array and write it out to a file: mathworks.com/matlabcentral/fileexchange/24093Ahmed Fasih

2 Answers

1
votes

the documentation on dlmwrite states:

Remarks

The resulting file is readable by spreadsheet programs.

The dlmwrite function does not accept cell arrays for the input matrix M. To export a cell array that contains only numeric data, use cell2mat to convert the cell array to a numeric matrix before calling csvwrite.

To export cell arrays with mixed alphabetic and numeric data, where each cell contains a single element, you can create an Excel spreadsheet (if your system has Excel installed) using xlswrite. For all other cases, you must use low-level export functions to write your data.

So either you write it as an Excel spreadsheet, or use have to write your own conversion function.

For example

A=[2; 3; 3;];
B=2*A;
C=cell(3,1);
C{1,1}='string1'; C{2,1}='string2'; C{3,1}='string3';

% First solution
f = fopen('filename.txt', 'w');
for n = 1:3
    fprintf(f, '%d\t%d\t%s\n', A(n), B(n), C{n});
end
fclose(f);

% Another solution
% create the table as a single cell array with only strings
C2 = [arrayfun(@num2str, [A, B], 'UniformOutput', false) C]'; % <- note the transpose

f = fopen('filename.txt', 'w');
fprintf(f, '%s\t%s\t%s\n', C2{:}); % <- every three entries are written as a line
fclose(f);
3
votes

Try the following:

% Open a file for writing (if you want to append to file use 'a' instead of 'w')
fid = fopen(file,'w');

for i = 1:size(A,1)
    fprintf(fid,'%d  %d  %s\n',A(i),B(i),C{i})
end

fclose(fid)

Hope this helps