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

조회 수: 12 (최근 30일)
Ramiro Barrantes
Ramiro Barrantes 2021년 10월 9일
댓글: Walter Roberson 2021년 10월 10일
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')

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by