Import .txt data into CELL ARRAY

I have text files with arrays of data:
{ Centroid = [[1 0 1],[0 1 0]] Ages= [10 20 30],Times = [ 3:00, 3:05] }
->Exact example, text file includes enclosed brackets '{ }'
I need to import this data into a (cell array?) in MATLAB, so that I can call the various labels and access their data.

2 commentaires

Paolo
Paolo le 17 Sep 2018
What would the desired cell array look like?
I don't have a particular idea, but some type of table in which I could call chunks of data.
'Centroid'
{[0 1 1]}
{[2 1 3]}
Etc: I'm not super familiar with Tables in MATLAB

Connectez-vous pour commenter.

Réponses (1)

Paolo
Paolo le 17 Sep 2018

0 votes

Try something like this:
raw = fileread('mytextfile.txt');
[~,tok]=regexp(raw,'([A-Z][a-z]+).*?(\[.*?(?=[ ,][A-Z}]))','match','tokens');
tokens = [tok{:}];
varnames = tokens(1:2:end);
data = tokens(2:2:end);
cell2table(data,'VariableNames',varnames)
1×3 table
Centroid Ages Times
___________________ ____________ _______________
'[[1 0 1],[0 1 0]]' '[10 20 30]' '[ 3:00, 3:05]'

6 commentaires

Philip
Philip le 18 Sep 2018
Modifié(e) : Philip le 18 Sep 2018
What is happening in that second row, can you explain?
[~,tok]=regexp(raw,'([A-Z][a-z]+).*?(\[.*?(?=[ ,][A-Z}]))','match','tokens');
Paolo
Paolo le 18 Sep 2018
I am happy to explain but before doing so can you just confirm that the output table is what you are after?
Philip
Philip le 18 Sep 2018
That would work fine, yes, as long as I can call those values.
Paolo
Paolo le 18 Sep 2018
The second line of code is a regular expression. It can be used to match pattern in strings. In the regular expression, there are two capturing groups. Those are used to extract the name of the variable and the data itself.
Perhaps you can try the regex demo live here ( link)
Please note that I am assuming that this pattern is consistent across your entire text file.
Philip
Philip le 20 Sep 2018
That's intense, thanks, I will have to play with it and lookup documentation to understand each component of this.
Question on output: Can you now call specific parts from the table? How would you do that: example
answer = table('Ages',array[0])
...
(answer = 10)
Would it be better/easier to use textscan? Especially for text files that are just one big array of numbers?
Thanks!

Connectez-vous pour commenter.

Catégories

Produits

Version

R2017b

Question posée :

le 17 Sep 2018

Commenté :

le 25 Sep 2018

Community Treasure Hunt

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

Start Hunting!

Translated by