How can I write a csv file by row or by column

14 views (last 30 days)
I am processing some data through a function whose output is a cell array of sequences of numbers, for example:
>> output
ans =
1×27 cell array
Columns 1 through 6
{4397×1 uint8} {2185×1 uint8} {1257×1 uint8} {682×1 uint8} {245×1 uint8} {689×1 uint8} ....
If write this to a file using the "writematrix" function, it will do one very long row.
I would like to write each one of the cells as a separate row or a separate column, such that the file will have only 27 rows or 27 columns. This would make it easier to read by other software for subsequent processing.
Any help appreciated.

Answers (1)

Akira Agata
Akira Agata on 10 Oct 2021
How about the following?
% Sample data (1-by-3 cell array)
output = {...
uint8(randi([0 255],100,1)),...
uint8(randi([0 255],200,1)),...
uint8(randi([0 255],300,1))};
% Find maximum length in the data
maxNum = max(cellfun(@numel, output));
% Prepare for arranging the data
output2 = nan(maxNum, numel(output));
% Store k-th data (output{k}) in k-th column of output2
for k = 1:numel(output)
nElement = numel(output{k});
output2(1:nElement, k) = double(output{k});
end
% Export the arranged data to Excel file
writematrix(output2,'a.xlsx')
  1 Comment
Walter Roberson
Walter Roberson on 10 Oct 2021
A different way of writing the same approach:
% Sample data (1-by-3 cell array)
output = {...
uint8(randi([0 255],100,1)),...
uint8(randi([0 255],200,1)),...
uint8(randi([0 255],300,1))};
% Find maximum length in the data
maxNum = max(cellfun(@numel, output));
%rearrange as rows and pad with nan
output2 = cell2mat(cellfun(@(C) [reshape(C,1,[]), nan(1, maxNum - numel(C))], output(:), 'uniform', 0));
% Export the arranged data to Excel file
writematrix(output2,'a.xlsx')

Sign in to comment.

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!