Reading cell array from excel table, which contains different sizes of doubles

I would like to read these columns as cell arrays, where the components are doubles, such as the following:
m_con = {[1,2,3],2,3};
I have tried xlsread but it didn't work.

 Respuesta aceptada

Adam Danz
Adam Danz el 12 de En. de 2021
Editada: Adam Danz el 12 de En. de 2021
There might be a smoother method but this works with the data from your image.
file = 'Book1.xlsx';
opts = detectImportOptions(file);
opts = setvartype(opts, 'char');
C = readcell(file,opts); % you can also try readtable()
numIdx = cellfun(@isnumeric,C);
C(numIdx) = cellfun(@num2str,C(numIdx),'UniformOutput',false);
Cnum = cellfun(@str2num,C,'UniformOutput',false)
Cnum =
3×4 cell array
{1×3 double} {1×3 double} {[ 1]} {[ 1]}
{[ 2]} {[ 2]} {1×2 double} {1×2 double}
{[ 3]} {[ 2]} {1×2 double} {1×2 double}
Cnum{1,1}
ans =
1 2 3

8 comentarios

Thank you so much!
By the way, when i try to import from a spreadsheet C returns as 3x3. Do you know where the problem could be?
C = readcell(filename,'Sheet','Table2',opts);
I meant like this
C = readcell(filename,opts,'Sheet','Tabelle2');
I would need the file to investigate.
I have figured that problem but came up with a new one. I have the following table from another file and i guess bucause of the empty spaces in the table i get an error like this: Error using str2num (line 35) Input must be a character vector or string scalar.
Is there a way to ignore the empty spaces and have the first two as 2x1 arrays?
This line from my answer identifies cell elements that are already numeric and is used to copy those values to the output cell array.
numIdx = cellfun(@isnumeric,C);
You can add an additional line that search for character vectors.
charIdx = cellfun(@ischar,C);
Cnum(charIdx) = cellfun(@str2num,C(charIdx),'UniformOutput',false)
*not tested
It works! Thank you so much for your help!
I have one last quastion. I tried to combine these two with an if condition but i still get en error. Do you know a better expression or is it completely false waht i did?
if ~isnumeric(C)
numIdx = cellfun(@isnumeric,C);
C(numIdx) = cellfun(@num2str,C(numIdx),'UniformOutput',false);
Cnum = cellfun(@str2num,C,'UniformOutput',false);
elseif ~ischar(C)
charIdx = cellfun(@ischar,C);
Cnum(charIdx) = cellfun(@str2num,C(charIdx),'UniformOutput',false);
end

Iniciar sesión para comentar.

Más respuestas (0)

Preguntada:

el 11 de En. de 2021

Comentada:

el 12 de En. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by