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.
댓글 수: 0
답변 (1개)
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
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 Center 및 File Exchange에서 Spreadsheets에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!