Kambiz
Kambiz

Reputation: 715

cell array of strings to matlab structure

I need to create a matlab structure as such ds=struct('name',{{'my_name_is'},{'matlab_thining_hair'}}) which stores as a 1x2 struct array with fields: name. A call to ds.name generates the output:

ds.name

ans = 'my_name_is'

ans = 'matlab_thining_hair'

Please note the single quotes in the output. They are important. That said, I need to create the above mentioned structure using the following variable: X = [1x46 char] [1x47 char] i.e., 1x2 cell, which I believe is actually a cell array of strings. Among other things, I've tried the following:

Y = cell2struct(X, 'name', 1)'

which results in a 1x2 structure array with fields name, however a call to Y generates the output:

Y.name

ans = my_name_is

ans = matlab_thining_hair

Note that the single quotes in the output are missing, and albeit both Y and ds are 1x2 struct arrays with fields name, the field values are not formatted the same and the structures also vary in their bytes size. How to format the field values as character arrays?

Upvotes: 3

Views: 3100

Answers (2)

Andrew Janke
Andrew Janke

Reputation: 23848

Stick your char strings in another layer of cells before calling cell2struct. Instead of:

X = { 'foo', 'bar' }

Try:

X = { {'foo'}, {'bar'} }

That is, a 1-by-2 cell whose cell contents are themselves cells, not chars. Then cell2struct(X, 'name', 1) should give you a struct array with fields of cell arrays.

If your existing X is a cellstr, I think you can just call num2cell on it to push each cell down into another layer of cell indirection.

Upvotes: 1

Navan
Navan

Reputation: 4477

In your first case you have created a struct with two fields whose values are cell arrays. The cell arrays are displayed with quotes.

In your second case your struct fields have char arrays which is what you want. Char arrays display without quotes.

You can verify this by typing in your command prompt {'abc'} and then 'abc'.

In your first case you can create non-cell array field values by passing the strings outside cell parenthesis.

ds=struct('name',{'my_name_is','matlab_thining_hair'})

Upvotes: 1

Related Questions