Transposing the output of writecell

8 次查看(过去 30 天)
Each element of my cell array consists of a vector of a different length. I want to write these vectors to a file. I do this by:
writecell(C,'C_data.csv')
That does the trick, except the output file has row vectors. I want column vectors, so I tried transposing the cell array:
writecell(C','C_data.csv')
That results in one long row in the output file. I also tried transposing the elements inside the array:
C = cellfun(@transpose,C,'UniformOutput',false);
writecell(C,'C_data.csv')
That doesn't seem to do anything. How do I output my content as column vectors of different length?
  1 个评论
Benjamin Thompson
Benjamin Thompson 2022-2-14
The difficulty is the cell contents having different lengths, which means at the end of the CSV file you will have data in some columns missing. How are you going to represent that in CSV. Can you post some sample input/output examples for what you are trying to do? Note that you can save and reload this data in the binary MAT file format easily.

请先登录,再进行评论。

采纳的回答

Voss
Voss 2022-2-15
编辑:Voss 2022-2-15
You can make a 2D cell array of size n_max-by-n_vectors, where n_vectors is the number of vectors in C and n_max is the length of the longest vector in C. Then fill it in from the top column-by-column with the contents of each vector in C:
C = {1 [1 2 3 4 5] [1 2 3]};
n = cellfun(@numel,C);
n_max = max(n);
n_vectors = numel(C);
C_aug = cell(n_max,n_vectors);
for ii = 1:n_vectors
C_aug(1:n(ii),ii) = num2cell(C{ii}(:));
end
writecell(C_aug,'C_data.csv');
show_csv_contents('C_data.csv');
1,1,1 ,2,2 ,3,3 ,4, ,5,
function show_csv_contents(fn)
fid = fopen(fn);
data = char(fread(fid).');
fclose(fid);
disp(data);
end
  3 个评论
Voss
Voss 2022-2-15
Did that answer work for what you wanted to do? If so, please mark the answer as 'Accepted'. Thanks!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Language Support 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by