How to properly read a csv saved cell array.
显示 更早的评论
Hi,
I am new with Matlab and I would like to know why I am not reading a cell array as I saved it. i.e. I have a cell of arrays (3834x1) and I saved it as csv file.
writecell(X_train_past, ...
strcat(train_data_path, 'past_features.csv'), ...
"Delimiter",";")

However, when reading the cell I got a cell of 926x864, totally different of the saved cell array. Is there any way to get the same shape when reading a cell as it was writen ?
opts = detectImportOptions(test_path);
opts.LineEnding = '\n';
C = readcell(test_path,opts);

Thanks a lot in advance,
Rafa
2 个评论
Stephen23
2024-8-26
Please upload both:
- the cell array in a MAT file
- the CSV file
by clicking the paperclip button.
the cyclist
2024-8-26
I believe that this code snippet will illustrate fundamental issue, at a more reasonable scale:
% Create a cell array where each element is a numeric array
rng default
x = cell(3,1);
x{1} = rand(2,5);
x{2} = rand(3,5);
x{3} = rand(3,5);
% Write to file
filename = 'past_features.csv';
writecell(x,filename,"Delimiter",";")
% Read back from file
opts = detectImportOptions(filename);
opts.LineEnding = '\n';
C = readcell(filename,opts);
采纳的回答
更多回答(1 个)
@Walter Roberson's answer is the canonical one, to be sure. A csv simply cannot store the cell array as you hoped (and naively coded) it would.
That being said, you may be able to very very kludgily reconstruct (approximately) what got stored in the CSV. They will not be exact (presumably due to some storage differences in floating point), but more importantly is not likely to generalize beyond your specific example (and my miniature version of it). Caveat emptor!
% Create a cell array where each element is a numeric array
rng default
x = cell(3,1);
x{1} = rand(2,5);
x{2} = rand(3,5);
x{3} = rand(3,5);
% Write to file
filename = 'past_features.csv';
writecell(x,filename,"Delimiter",";")
% Read back from file
opts = detectImportOptions(filename);
opts.LineEnding = '\n';
C = readcell(filename,opts);
% Reconstruct it. Relies on the fact that during reconstruction, you know
% the size the cell contents were going in.
[r,c] = size(x);
x_recon = cell(r,c);
for nr = 1:r
tmp = [C{nr,:}];
tmp(isnan(tmp))=[];
x_recon{nr} = reshape(tmp,size(x{nr}));
end
% Compare one row, to illustrate
x{1}
x_recon{1}
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!