Reputation: 179
in Matlab I have one 100X4000 mat which contains doubles and I have a 100X1 cell of chars. now the problem is how can I write all together in a CSV file. Matlab doesn't let me to do that. a shorter example is like this: first mat
0 1 2
0 0 0
0 5 3
9 0 7
0 4 0
second cell:
apple
banana
cherry
peach
other
the expected result (A) is:
0 1 2 apple
0 0 0 banana
0 5 3 cherry
9 0 7 peach
0 4 0 other
final goal is to do this:
csvwrite('dataLabels.csv',A);
Upvotes: 2
Views: 154
Reputation: 1960
The code is as simple as follows:
% Toy Example Data
B = [0 1 2; 0 0 0; 0 5 3; 9 0 7; 0 4 0];
C = { 'apple' 'banana' 'cherry' 'peach' 'other' }';
B = num2str(B,'%i %i %i');
dlmwrite( 'dataLabels.csv', [B repmat( char(' '), length(C), 1 ) char( C{:} )], '' );
So what you want to do is change your matrix B
into a char with your desired spacing. That's what the num2str
function does with those parameters. Then you can use dlmwrite
to delimit with no spacing. The code char( C{:} )
simply converts the cell into a char.
The code repmat( char(' '), length(C), 1 )
is just to put a space in between the matrix B
and char cell C
.
Results
0 1 2 apple
0 0 0 banana
0 5 3 cherry
9 0 7 peach
0 4 0 other
Upvotes: 1
Reputation: 11
You can use fopen(filepath, w)
and fprintf(fileId, data)
to write several matrices as strings in a csv file.
Example:
function createCSV(name, data1, data2)
fileId = fopen(path/to/file.csv, 'w');
[x, y] = size(data);
for i = 1:x
for j = 1:y
fprintf(fileId, num2str(data(x, y)));
fprintf(fileId, ',');
end
fprintf(fileId, num2str(data2(x)));
fprintf(fileId, '\n');
end
end
Upvotes: 0