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

12 次查看(过去 30 天)
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.

回答(1 个)

Akira Agata
Akira Agata 2021-10-10
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 个评论
Walter Roberson
Walter Roberson 2021-10-10
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')

请先登录,再进行评论。

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by