Create cell from character array
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Dear all,
I am reading lines from a text file using fgetl(), and I come across the following line in the file:
{[1, 2, 3], 'hello'}
If I read this in as the variable C, I get:
C =
{[1, 2, 3], 'hello'}
>> whos C
Name Size Bytes Class Attributes
C 1x15 30 char
I can easily convert this to a cell:
>> C = cellstr(C);
>> whos C
Name Size Bytes Class Attributes
C 1x1 156 cell
I would like to use C later to access its contents. Currently, if I try to access C I get the following:
>> C{1}
ans =
{[1, 2, 3], 'hello'}
It looks like the text line was read in and then converted to a character cell. However, I need to be able to access the first element as a numeric array and the second element as a character array. How can I do this?
Ultimately, I should be able to read in any cell, regardless of its contents (character, numeric, etc.) and sill be able to access the individual elements. I don't want just a single character array defined as a cell.
Many thanks in advance,
Louis
0 Commenti
Risposte (2)
Star Strider
il 16 Dic 2016
It took a bit of experimenting to reproduce your cell.
See if this does what you want:
C{1} = {[1, 2, 3], 'hello'};
num = cell2mat(C{1}(1)) % Option #1
numc = C{1}(1); % Option #2
num = numc{:}
4 Commenti
Star Strider
il 18 Dic 2016
Try this:
Cs = regexp(C{:}, '\{|\[|\]|\}|\', 'split')
It gives:
Cs =
'' '' '1, 2, 3' ', 'Hello'' ''
The problem is that setting up the comma as a delimiter separates the numbers. Not doing it keeps the comma in the 'Hello' string. I can’t find any available logic expressions in the regexp documentation that will give the ‘pure’ output you want.
Jan
il 18 Dic 2016
Modificato: Jan
il 18 Dic 2016
Start with the string:
C = '{[1, 2, 3], ''hello''}'
You want to get the numerical array
D = [1,2,3]
correct?
D = sscanf(C(3:end), '%g,').'
Et voila.
Then you write:
Ultimately, I should be able to read in any cell, regardless of its
contents (character, numeric, etc.) and sill be able to access the
individual elements.
Wow, you want to rebuild a Matlab interpreter. This is a really big job. Nested cells containing struct array with mutliple fields, user-defined objects and perhaps function handles for anonymous functions, which create HG2 objects on the fly?!
Don't do this. Do not try to reinvent the Matlab interpreter. If you need to interprete complicated strings as code to create a cell, write an M-file and let Matlab do the job it is designed for.
Not that you can parse the string dynamically using eval, but take this warning seriously:
Don't do this!
Vedere anche
Categorie
Scopri di più su Text Files in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!