Azzera filtri
Azzera filtri

Transposing the output of writecell

8 visualizzazioni (ultimi 30 giorni)
L'O.G.
L'O.G. il 14 Feb 2022
Commentato: L'O.G. il 15 Feb 2022
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 Commento
Benjamin Thompson
Benjamin Thompson il 14 Feb 2022
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.

Accedi per commentare.

Risposta accettata

Voss
Voss il 15 Feb 2022
Modificato: Voss il 15 Feb 2022
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 Commenti
Voss
Voss il 15 Feb 2022
Did that answer work for what you wanted to do? If so, please mark the answer as 'Accepted'. Thanks!
L'O.G.
L'O.G. il 15 Feb 2022
Yes, thank you. Done. :)

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by