Convert from cell of a table to an array

2 vues (au cours des 30 derniers jours)
Cameron Dyson
Cameron Dyson le 30 Oct 2020
Commenté : Cameron Dyson le 30 Oct 2020
I am importing data from an excel spreadsheet as follows:
options = readtable('options.xlsx');
Some of the excel cells contain descitions of arrays like "[1,2,3]". The cell from readtable would then be:
{'[1,2,3]'}
I would like to convert this to an array of doubles like
[1,2,3]
How can I go about doing this?

Réponse acceptée

Sindar
Sindar le 30 Oct 2020
Modifié(e) : Sindar le 30 Oct 2020
It gets tricky with different variable types and widths, but hopefully this helps. Worst case, you build up the new table element by element:
% build example like your table
t=table();
t{1,1}={'[1,2,3]'};
t{1,2}={'[4,5,6,7]'}
t =
1×2 table
Var1 Var2
___________ ___________
{'[1,2,3]'} {'[4,5,6,7]'}
% start a new table
t2=table();
% convert the text in the cell to an array:
t2{1,1}=str2num(t{1,1}{1});
t2{1,2}=str2num(t{1,2}{1})
t2 =
1×2 table
Var1 Var2
___________ ________________
1 2 3 4 5 6 7
  2 commentaires
Sindar
Sindar le 30 Oct 2020
FYI: if a table has arrays as elements, they need to be the same width down columns. This will error:
t=table()
t{1,1}={'[1,2,3]'}
t{2,1}={'[4,5,6,7]'}
t2=table()
t2{1,1}=str2num(t{1,1}{1})
t2{2,1}=str2num(t{2,1}{1})
Cameron Dyson
Cameron Dyson le 30 Oct 2020
Thank you, its working for me now!

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by