Reputation: 99
all,
I have a cell array with 5 cells as shown below:
<18250x1 int32> <18250x1 int32> <18250x1 int32> <18250x1 double> <18250x1 double>
In each cell, there are numbers of 18250 rows and 1 column.
Now I want to write these data into a csv file, with 18250 rows, 5 columns.
I've tried Cell2mat which only allows the array to have the same data types. I need to maintain the data types of int or double in the output. Anybody know how to solve this problem?
Thanks, James.
Upvotes: 1
Views: 1350
Reputation: 11812
Just creating a cell array comparable to yours:
>> A = { int32(randi(100,100,1)) , int32(randi(100,100,1)) , int32(randi(100,100,1)) , rand(100,1)*100 , rand(100,1)*100 }
A =
[100x1 int32] [100x1 int32] [100x1 int32] [100x1 double] [100x1 double]
You can convert your int32
column to double before writing them to file with dlmwrite
. For the first 3 columns, Matlab will recognize that they are integers and will adjust the write output accordingly. For the last 2 columns, Matlab will write double precision numbers at the precision you specify:
B = [double(cell2mat(A(:,1:3))) , cell2mat(A(:,4:5)) ] ;
dlmwrite('testwrite.csv', B , 'precision',10)
This output in my case:
26,100,1,87.70487234,93.37256595
40,23,85,35.31418129,81.09500322
8,66,93,44.94435566,48.45482718
69,61,78,96.35302868,75.67492101
... and so on
Upvotes: 2
Reputation: 104565
This will be slightly complicated because each cell has a different data type. The only way I can think to respect the data type is to manually create your own CSV file by opening up a file for writing, then manually writing your entries into the CSV file one row at a time. Remember, CSV files are comma separated, so a number is separated by a comma, and each row is separated by a carriage return.
You would basically go through each row for a particular cell, then write your data as is by respecting the data type and putting in a comma between each value and manually placing a carriage return for each row of your data. Assuming your data is stored in a cell array called M
, you can do something like this:
fid = fopen('test.csv', 'w');
for idx = 1 : 18250
val1 = M{1}(idx);
val2 = M{2}(idx);
val3 = M{3}(idx);
val4 = M{4}(idx);
val5 = M{5}(idx);
fprintf(fid, '%d,%d,%d,%f,%f\n', val1, val2, val3, val4, val5);
end
fclose(fid);
The above code opens up a file for writing called test.csv
by using fopen
. This returns a link to the file which we want to write to. Then, we iterate through each corresponding element in each cell array, then manually write this out as a row in the file. Each number is comma separated and makes up one row in your CSV file by respecting the data type for each number. Once we finish, we manually place a carriage return and go to the next row until we finish. We then close the file to signify that we have stopped writing to the file, and we can apply the changes.
Try that and see if that works!
Upvotes: 3